Trimming Text After Label Edit

ListView is beautiful control. Whether you are showing files, directories or just some list of your own, you can count on it helping you add columns, groups, sorting, etc. It even allows for rename.

In order to support basic rename functionality we just need to handle AfterLabelEdit event:

private void listView_AfterLabelEdit(object sender, LabelEditEventArgs e) {
if (e.Label == null) { return; }
//do something with e.Label (e.g. rename file)
}

But what if we want to ignore whitespaces after the text?

For example, every time somebody tries to rename file to " My new name " we should actually remove all that extra spacing and use "My new name". Obvious solution would be to do e.Label = e.Label.Trim(). However, that code does not even compile. Time for tricks...

If we detect whitespace we can just cancel everything. That will prevent ListView from making any changes to our item. Then we can be sneaky and change item ourselves:

private void listView_AfterLabelEdit(object sender, LabelEditEventArgs e) {
if (e.Label == null) { return; }
var trimmed = e.Label.Trim();
if (!(string.Equals(trimmed, e.Label))) {
e.CancelEdit = true;
listView.SelectedItems[0].Text = trimmed;
}
//do something with variable trimmed
}

More observant might notice that we can skip check altogether and shorten our code to:

private void listView_AfterLabelEdit(object sender, LabelEditEventArgs e) {
if (e.Label == null) { return; }
var trimmed = e.Label.Trim();
e.CancelEdit = true;
listView.SelectedItems[0].Text = trimmed;
//do something with variable trimmed
}

Full sample is available for download.

PS: For homework find why we need (e.Label == null) { return; } at start of an AfterLabelEdit event handler?

One thought to “Trimming Text After Label Edit”

Leave a Reply to BoyWonder Cancel reply

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