Not seeing all the binding code, I will have to make some assumptions, but I can understand what might keep your code from working as desired, and I have created an example to make it work as desired.
My first is assumption is how you create the binding source, so let's assume this:
-
List<string> list01 = new List<string>();
-
list01.Add("AAA");
-
list01.Add("BBB");
-
list01.Add("CCC");
-
Binding Source bindingSource2 = new BindingSource(list01, "");
-
this.listBox1.DataSource = bindingSource2;
-
As such, your list box would display the items correctly, because by default the list box calls the "ToString()" method on the objects it is bound to in order to figure out what to display.
Your code to add some items dynamically via the BindingSource will work fine ASSUMING you have added this line, which I have not seen, AFTER adding and BEFORE trying to select the new items:
-
this.bindingSource2.ResetBindings(false);
-
So far so good. So I create a dummy object and change the source list to List<MyThing>:
-
public class MyThing {
-
string s;
-
int i;
-
public MyThing(string s, int i) {
-
this.s = s;
-
this.i = i;
-
}
-
public string SomeString { get { return this.s; } }
-
public int SomeInt { get { return this.i; } }
-
}
-
So to add some initial objects it will look like:
-
list01.Add(new MyThing("X", 24));
-
// etc
-
And modifying your dynamic add/select code would look like:
-
for (int i = cnt; i < (cnt + 10); i++) {
-
bindingSource2.List.Add(new MyThing(i.ToString(), i));
-
}
-
As such, this will not display anything properly.
The "MyThing" object does not have a ToString() override.
The trick to get this to display properly is to add this line when you do your intial databinding:
-
bindingSource2 = new BindingSource(list01, "");
-
this.listBox1.DisplayMember = "SomeString";
-
this.listBox1.DataSource = bindingSource2;
-
Without posting all my sample code, which may have some minor difference from yours, this works. When I add the new MyThings, it displays the "SomeString" property of them, and selects the new ones I add.
By default a ListBox calls ToString() on the object it is bound to, unless you specify the DisplayMember property which is the property name of your bound object's property which you want to display. (The property of the items in the bound list, not a property of the list itself.)
Let me know if it still does not work or if you need clarification.
Mike