Occasionally, you need to allow the fired event to do its job (within your created handler) and upon its exit you want to do certain actions post-event. That is, you want to schedule certain actions to take place right after the event. The best way to do this is to call the BeginInvoke() method.
Here's an example.
Say that you are editing a ListViewItem's text in a ListView. In the AfterLabelEdit event handler, you investigate the changes made and based on those changes you may want to remove the item. The quickest way to do this would be:
private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
e.CancelEdit = true;
ListViewItem item = listView1.Items[e.Item];
item.Remove();
}
This works fine only if you are not interested in preserving the changes made while editing: your changes and the item are lost forever.
If, however, you wish to preserve the changes (e.g. you want to remove the edited item from this particular list, but add it to a different one), another apporach is needed.
First, you need to declare a private delegate as follows:
private delegate void RemoveItemDelegate(ListViewItem item);
Then, declare a private method to implement the delegated type:
private void RemoveItem(ListViewItem item)
{
item.Remove();
}
Finally, within your AfterLabelEdit event handler add this code:
private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
ListViewItem item = listView1.Items[e.Item];
listView1.BeginInvoke(new RemoveItemDelegate(RemoveItem), item);
}
The RemoveItem() method will be called asynchronously after the event handler has exited.
Voila!
Saturday, July 29, 2006
Friday, July 28, 2006
Start here...
This blog is intended to be an "explorer's diary" of C#, ASP.NET and SQL 2005, recording 'how-to' tips and tricks from the world of the .NET framework v2.x and beyond...
Subscribe to:
Posts (Atom)
