【问题标题】:Listbox doesn't update after adding from list从列表添加后列表框不更新
【发布时间】:2017-12-13 08:21:12
【问题描述】:

编辑

感谢@omaxel,它现在可以工作了

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

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

还有@周明的

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

原帖

我从列表中添加项目后,表单中的列表框没有更新。它确实向列表中添加了一个值,并且整数(beschikbarePlekken)按预期工作。你可以帮帮我吗?这是我的代码。

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);
    }

}

【问题讨论】:

  • 再次尝试设置ListBox的数据源。在UIDList.Add(UID); 之后添加lbUID.DataSource = UIDList;
  • @Nino 仍然无法正常工作,很遗憾。

标签: c# list arduino listbox


【解决方案1】:

您应该使用BindingList&lt;string&gt; 而不是List&lt;string&gt;。因此,每当您向UIDList 添加项目时,列表框都会更新。

来自微软文档:

BindingList&lt;string&gt;:提供支持数据绑定的通用集合。

将您的 UIDList 变量声明/初始化更改为:

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

另外,记得在主线程上调用 ListBox 控件的Add 方法。在您的 UpdateList 方法中,您可以使用

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

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

【讨论】:

  • 很高兴为您提供帮助 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多