Quokka
Quokka

Reputation: 13

Listbox doesn't update after adding from list

Edit

It now works thanks to @omaxel's

BindingList<string> UIDList = new BindingList<string>();

and

lbUID.Invoke((MethodInvoker)delegate
{
  UIDList.Add(UID);
});

and @Ming Zhou's

//reset the DataSource
lbUID.DataSource = null;
lbUID.DataSource = UIDList;

Original Post

The listbox in my form doesn't update after I add an item from a list to it. It does add a value to the list and the integer (beschikbarePlekken) is working as intended. Could you help me? Here is my code.

public partial class Form1 : Form
{
    // Variabelen
    SerialPort port;
    int beschikbarePlekken = 255; // Beschikbare parkeerplekken
    string UID = " ";
    List<string> UIDList = new List<string>();

    public Form1()
    {
        InitializeComponent();
        port = new SerialPort("COM12", 9600);
        port.DataReceived += incoming;
        port.Open();
        lbUID.DataSource = UIDList;
    }

    private void incoming(object sender, SerialDataReceivedEventArgs e)
    {
        UID = port.ReadLine().Trim();

        if (UID.Length == 0)
        {
            return;
        }

        UpdateList(UID);
    }

    delegate void SetLabel();

    public void UpdateList(string UID)
    {
        if (!UIDList.Contains(UID) && UIDList.Count < beschikbarePlekken)
        {
            UIDList.Add(UID);
            Console.WriteLine(UID);
            lblPlek.Invoke(new SetLabel(SetLabelMethod));
        }
    }

    void SetLabelMethod()
    {
        lblPlek.Text = "Beschikbare plekken: " + (beschikbarePlekken - UIDList.Count);
    }

}

Upvotes: 1

Views: 62

Answers (1)

Omar Muscatello
Omar Muscatello

Reputation: 1301

You should use BindingList<string> instead of List<string>. So, whenever you add an item to UIDList, the listbox will be updated.

From Microsoft Docs:

BindingList<string>: Provides a generic collection that supports data binding.

Change your UIDList variable declaration/initialization to:

BindingList<string> UIDList = new BindingList<string>();

Also, remember to call the Add method of the ListBox control on the main thread. In your UpdateList method you could use

if (!UIDList.Contains(UID) && UIDList.Count < beschikbarePlekken)
{
    lbUID.Invoke((MethodInvoker)delegate
    {
        UIDList.Add(UID);
    });

    lblPlek.Invoke(new SetLabel(SetLabelMethod));
}

Upvotes: 1

Related Questions