none
BindingList and ListBox behaviour..

    Question

  • Hi,

    I have a ListBox that is bound to a BindingList collection. This works great. 

    My only grief occurs when the first item enters the collection. The default behavior of the ListBox is to select that item - yet, this does not raise the SelectedIndexChanged event. I assume this is because the SelectedIndex is initially set to null; on becoming anything but null, the index isn't actually changed; rather assigned. How can I stop the default behavior of selecting (highlighting) the first initial item added to the ListBox?

    If my assumption is wrong, please shed some light?

    WulfgarPro
    Wednesday, January 26, 2011 1:52 AM

Answers

All replies

  • bump
    Thursday, January 27, 2011 12:47 AM
  • Hi WulfgarPro,

    Base on your description, as you have binded the datasource into the listbox and I am not sure how to add the item into the collection. Here is my test, I use the button to add new item into the datasource. When I add, it will appear in the last item of the listbox, and will not be selected.

     BindingList<String> list = new BindingList<string>();
    
        private void Test()
        {
          list.Add("John");
          list.Add("Peter");
          list.Add("Bush");
          list.Add("Ding");
    
          this.listBox1.DataSource = list;
        }
    
        private void button2_Click(object sender, EventArgs e)
        {
          list.Add("Mike");
        }

    You can have a try. If I have any misunderstanding, please feel free let me know. Thanks.

    Sincerely,
    Vin Jin


    Vin Jin [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, January 27, 2011 6:26 AM
  • Hi Vin Jin,

    Try something like the following:

     BindingList<string> _list = new BindingList<string>();
    
     public TestClass() {
    
      listBox1.DataSource = _list;
    
      AddItems();
    
     }
    
     public void AddItems() {
    
      _list.Add("test");
    
      _list.Add("test");
    
      _list.Add("test");
    
     }

    You will notice the first item in listBox1 is selected by default when the form loads.

    WulfgarPro

    Thursday, January 27, 2011 9:47 AM
  • SelectedIndex = -1
    Success
    Cor
    • Marked as answer by WulfgarPro Thursday, January 27, 2011 10:55 AM
    Thursday, January 27, 2011 10:48 AM
  • Thanks Cor. This does what I need it to do.

    WulfgarPro

    Thursday, January 27, 2011 10:55 AM
  • If you dont want that anyone items will get selected on the load, use Cor`s solution:

    this.listBox1.SelectedIndex = -1;

    Thursday, January 27, 2011 10:56 AM