Updating a list

Gloops

Well-known member
Joined
Jun 30, 2022
Messages
137
Programming Experience
10+
Hello everybody,

I wonder whether I missed something.

A ListBox is based on a list:
Declaration of a list, to load in a ListBox:
        List<Window> windows = new List<Window>();

In a .Net 6 project, I browse the list to load the ListBox:
Loading the ListBox while loading the list:
                 //while reading a file:
                while((line = sr.ReadLine())!=null)
                {
                    i++;
                    string[] spl = line.Split(';');
                    ListItem li = new ListItem(spl[0].Replace("\"", ""), spl[1].Replace("\"", ""));
                    listBox1.Items.Add(li);
                }

Just after adding li to the ListBox, I add an element to the windows list, but this will only be used when clicking on the ListBox.

So, when deciding to remove an element:
Remove an element from the ListBox that has been loaded element by element:
                        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
                        listBox1.Refresh();

This has at least the interest of being easy (so long I do not forget to remove an element in windows when I remove one from listBox1).

When migrating the project to .Net 4.7.2, I took the occasion to base the ListBox on the windows list.
Basing the ListBox on the windows list:
                listBox1.DataSource = windows;

But if I do that, I cannot remove an element by listBox1.Items.RemoveAt(listBox1.SelectedItem): this is not possible when there is a DataSource.

But I thought I could do this:
Remove an element from the list and refresh the ListBox:
windows.RemoveAt(listBox1.SelectedIndex);
windows.Refresh(); //I do not remember whether this exists
listBox1.Refresh(); // this does

But then, at a moment I had two elements in windows and three in listBox1, even though windows was the DataSource of listBox1.

So, I had to do this:
The real way to update a ListBox that has a DataSource:
                        listBox1.DataSource = null;
                        listBox1.DataSource = windows;
                        listBox1.DisplayMember = "Title";
                        listBox1.ValueMember = "WindowHandle";

For yes, changing the DataSource also causes to forget DisplayMember and ValueMember.

Did I miss anything that would have allowed something more simple?
 
Last edited:
Solution
Put the your list into an BindingList<T>. Then you can update the list and the ListBox will update when you remove items from the underlying list.


Or implement IBindingList on your own:

Or put your data into a DataTable instead of a List<T>.
Put the your list into an BindingList<T>. Then you can update the list and the ListBox will update when you remove items from the underlying list.


Or implement IBindingList on your own:

Or put your data into a DataTable instead of a List<T>.
 
Solution
Back
Top Bottom