Trimming Text in AfterLabelEdit

Editing text of ListView item is quite easy. Just set LabelEdit = True and you are good. This will allow user to change text of item and it will even let us validate it in AfterLabelEdit handler. But can we additionally adjust edited text?

Most obvious choice would be setting e.Label to some other value. That will unfortunately never compile since Label property is read-only. Next guess will be just hijacking AfterLabelEdit and editing text in code. Something like this:

if (e.Label == null) { return; }
var text = e.Label.Trim();
if (string.IsNullOrEmpty(text)) {
e.CancelEdit = true;
} else {
list.Items[e.Item].Text = text;
}

And this works - almost.

Editing label at this point does not really matter. Whatever you write into Text property will be overwritten with e.Label once AfterLabelEdit handler is returns.

In order to handle things our self we just need to pretend that we canceled original edit:

if (e.Label == null) { return; }
var text = e.Label.Trim();
if (string.IsNullOrEmpty(text)) {
e.CancelEdit = true;
} else {
list.Items[e.Item].Text = text;
e.CancelEdit = true;
}

Full code is here.

Leave a Reply

Your email address will not be published. Required fields are marked *