How to prevent ListBox.SelectedIndexChanged event?

后端 未结 7 1467
时光说笑
时光说笑 2020-12-16 11:37

I am using a listbox in my C#2.0 windows forms application. The method to populate the list box is

    private void PopulateListBox(ListBox lb, ReportColum         


        
7条回答
  •  借酒劲吻你
    2020-12-16 12:05

    You should be aware that even if you do not handle the event, the first item in the list will still be selected automatically when assigning the DataSource property. In order to force the user to make a selection you will need to unselect the automatically selected item.

    If your SelectedIndexChanged event handler triggers some functionality when an item is selected you may still want to block this from being executed. One way to do that is to keep track of whether the code is currently populating the listbox or not. If the SelectedIndexChanged event is triggered while the listbox is being populated, you can avoid performing those actions:

    private bool _populating = false;
    private void PopulateListBox(ListBox lb, ReportColumnList reportColumnList)
    {
        _populating = true;
        lb.DataSource = reportColumnList.ReportColumns;
        lb.DisplayMember = "ColumnName";
        lb.ValueMember = "ColumnName";
    
        // clear the automatically made selection
        lb.SelectedIndex = -1;
        _populating = false;
    }
    
    private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!_populating)
        {
            // perform the action associated with selecting an item
        }
    
    }
    

提交回复
热议问题