开发者

c# event handler on a listview

I would like to create an event handler in a listview. I mean I would like to call a function every time I have a new element in my listview. Can someone help me how to do it? I don't need a click event handler. The event handler I would like it to be automatically generated by the code (the ithem from the listview to be selected and then a new method to be called). The element in the listview looks like: element1 name surname (this is on the fir开发者_运维技巧st row). THx

How to create the handler for this function ?

private void listview1_SelectedIndexChanged(object sender, EventArgs e)
{ 
   for (int x = 0; x < listview1.Items.Count; x++)
   { 
      if (listview1.Items[x].Selected) 
         MessageBox.Show(listview1.Items[x].SubItems[1].Text);
   }
}


As Henk Holterman pointed out, the method you posted in your question, listview1_SelectedIndexChanged, IS an event handler. If it's not doing what it's supposed to, that could be because it's not attached to the corresponding event of listview1.

If the method already exists in the .cs file containing the code for your form, you need to attach it to the SelectedIndexChanged event of your ListView. To do this, select the control, then click on the lightning icon in the properties panel. Find the event (SelectedIndexChanged) in the list, then click on the arrow on the right and select listview1_SelectedIndexChanged.

Update:

Since you're adding the ListView programatically, you can assign the handler as follows

listView1.SelectedIndexChanged += listview1_SelectedIndexChanged;

As for your crash, I can't really think of anything off the top of my head. Maybe you could post the text of the exception?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜