简体   繁体   中英

Select Index Changed event is triggering two times

Here is a sample of my code:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count < 1)
    {
        MessageBox.Show("Please select an item first.");
    }
    else
    {
        string name = listView1.SelectedItems[0].SubItems[0].Text;
        Binddata(name);
    }
}

public void Binddata(string name)
{
    textBox1.Text=name;            
}

My Windows From will look like this:

形成

When I click on Item1 for the first time the textbox is displaying Item1. But then if I click on Item2, the number of selected items is becoming "0", so it is showing the message as "Please select an item first." and if I press ok, again the event is getting triggered and Item2 is getting binded.

Please help me out in this if I am missing any thing. Thanks in Advance.

Not sure why that happens, I think it fires once for unselecting the previous selected item, and second time for selecting new item.

As a workaround use Timer like this.

    private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var timer = new System.Windows.Forms.Timer() { Interval = 50 };
        EventHandler handler = null;
        handler = (x, y) =>
        {
            timer.Tick -= handler;
            timer.Enabled = false;
            timer.Dispose();

            if (listView1.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select an item first.");
            }
            else
            {
                string name = listView1.SelectedItems[0].SubItems[0].Text;
                Binddata(name);
            }
        };
        timer.Tick += handler;
        timer.Enabled = true;
    }

This is normal behavior. The only abnormal part is the fact that you are throwing a MessageBox when no item is selected. The ListView can have zero items selected and you need to handle that gracefully.

If you don't like this behavior you should use the ListBox control which can always require 1 item selected and won't throw multiple SelectedIndexChanged events.

According to MSDN :

When the user selects an item without pressing CTRL to perform a multiple selection, the control first clears the previous selection. In this case, this event occurs one time for each item that was previously selected and one time for the newly selected item.

You can check if any item is selected in other event handler such as button click.

This is normal behavior of single-select control. Refer the link for more details:

http://www.knowdotnet.com/articles/listviewselectedindexchanged.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM