3

I have a ListView in a C# based win-form project. Is it possible to limit the maximum length of the title of all ListViewItem inside the ListView ?

UPDATE

I mean the input length , I set the item to editable , so users can rename the items

UPDATE2

Right , It's called "the text" of that item , not the title.

daisy
  • 22,498
  • 29
  • 129
  • 265
  • Yes... you do control what goes into the ListView, don't you? So just do not allow in any items with a title that is longer than your maximum. Or am I misunderstanding your question? – Roy Dictus Apr 04 '12 at 07:14
  • try this [c# limit the length of a string](http://stackoverflow.com/questions/3825979/c-limit-the-length-of-a-string) – PresleyDias Apr 04 '12 at 07:59

2 Answers2

3

You can utilise the label after edit event of a listview. Here is a sample.

private void listview1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
    try
    {
        const int maxPermittedLength = 1;

        if (e.Label.Length > maxPermittedLength)
        {
            //trim text
            listview1.Items[e.Item].SubItems[0].Text = listview1.Items[e.Item].SubItems[0].Text.Substring(0, maxPermittedLength); //or something similar

            //or

            //show a warning message

            //or

            e.CancelEdit = true; //cancel the edit
        }
    }
    catch (Exception ex)
    {

    }
}

Remember, its tricky, not straightforward, you will have to take care of a few exceptions, but thats homework.. The above code is not a working code, but you have the idea now how to go about it. Read the documentation well, it has a nice example and a warning associated with this event.

nawfal
  • 70,104
  • 56
  • 326
  • 368
0

What do you mean ListViewItem's title ? is it the item text you mean ? I believe whatever retrievable is fixable and controllable. If it is the item text, you can write a check method

public string SimplifyTxt(string input)
{
    if(input.Length>LIMIT_NUMBER)
    {
       //please shorten the string before display
    }
    return retStr;
}

and it then can be assigned as

listview1.items.add(new Listviewitem{Text=retVal});
Cafebabee
  • 1
  • 3