I have simple program like this:
public static ObservableCollection<string> Client= new ObservableCollection<string>();
[STAThread]
static void Main()
{
Client.Add("Item1");
Client.CollectionChanged += Clients_CollectionChanged; ;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(form_m = new Mainwindow());
form_m.Close();
}
static void Clients_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
form_m.Program_console_1("Collectionchanged: " + e.NewItems.Count);
}
static void display_socket() {
try {
form_m.listBox1.DataSource = new BindingSource(Client, null);
}
catch (Exception e) {
form_m.Program_console_1("Display Binding Error: "+e.ToString());
}
}
public static void Item_add_btn_Click(object sender, System.EventArgs e)
{
Socket sock = null;
form_m.Program_console_1("New Socket Added" + e.ToString());
clients.Add("Third Socket",sock);
Client.Add("Item2");
}
I have created a windows form using the class form_m. When initialized a Listbox- listbox1 is created. I am trying to bind listbox1 to a collection such that when the collection is changed (item added or removed) listbox1 is changed. I have been searching this forum for a week now but I still can't get this to work.
For testing purpose I am using a simple ObservableCollection. When the form is initiated. Listbox shows Item1. When I add a new item using Item_add_btn_Click method. I expect Listbox to show Item1 and Item2 which does not happen.
If I replace ObservableCollection with BindingList, It works like a fine. Item2 is updated in Listbox as soon as Item_add_btn_Click is called.
Why does this happen?