如何刷新在C#中的WinForms一个列表框的数据源 [英] How to refresh DataSource of a ListBox in C# WinForms

查看:293
本文介绍了如何刷新在C#中的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.

什么是错我的code?

What is wrong with my code?

感谢。

推荐答案

listbox1.DataSource 属性查找值的变化,但通过分配相同的列表中的所有时间价值赢得'T真正改变。

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

您可以使用的BindingList&LT; T&GT; ,而不是你的名单,其中,T&GT; ,自动识别新项目补充道。您ShowData()方法必须在启动时被调用一次。

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

这篇关于如何刷新在C#中的WinForms一个列表框的数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆