Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh DataSource of a ListBox

Tags:

c#

.net

winforms

Form has one Combobox and one ListBox. When the "Add" button is clicked, I want to add the selected item from the ComboBox to the ListBox.

public partial class MyForm:Form {     List<MyData> data = new List<MyData>();     private void ShowData()     {        listBox1.DataSource = data;        listBox1.DisplayMember = "Name";        listBox1.ValueMember = "Id";     }      private void buttonAddData_Click(object sender, EventArgs e)     {        var selection = (MyData)comboBox1.SelectedItem;        data.Add(selection);        ShowData();     } } 

With this example, the selected item is replaced with the new selection inside ListBox. I need to add the item to the list.

What is wrong with my code?

like image 653
panjo Avatar asked Jul 12 '13 12:07

panjo


People also ask

How does ListBox work in C#?

In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. The ListBox class is used to represent the windows list box and also provide different types of properties, methods, and events.


1 Answers

listbox1.DataSource property looks for value changes but by assigning the same list all the time the value won't really change.

You can use a BindingList<T>, instead of your List<T>, to automatically recognize new items added. Your ShowData() method must be called once at startup.

public partial class MyForm:Form {     public MyForm(){         InitializeComponent();         ShowData();     }      BindingList<MyData> data = new BindingList<MyData>();      private void ShowData()     {        listBox1.DataSource = data;        listBox1.DisplayMember = "Name";        listBox1.ValueMember = "Id";     }      private void buttonAddData_Click(object sender, EventArgs e)     {        var selection = (MyData)comboBox1.SelectedItem;        data.Add(selection);     } } 
like image 50
dwonisch Avatar answered Sep 24 '22 16:09

dwonisch