Limiting the maximum text length of ListViewItem?

Go To StackoverFlow.com

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.

2012-04-04 07:08
by daisy
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 2012-04-04 07:14
try this c# limit the length of a stringPresleyDias 2012-04-04 07:59


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.

2012-04-04 09:04
by nawfal


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});
2012-04-04 07:21
by Cafebabee
Ads