如何刷新列表框的数据源 [英] How to refresh DataSource of a ListBox

查看:109
本文介绍了如何刷新列表框的数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

窗体具有一个组合框和一个列表框。单击添加按钮时,我想将ComboBox中的选定项添加到ListBox。

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

在此示例中,所选项目被替换为ListBox中的新选择。我需要将该项目添加到列表中。

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

我的代码有什么问题?

推荐答案

listbox1.DataSource 属性用于查找值更改,但是通过始终分配相同的列表,值不会真正更改。

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

您可以使用 BindingList< T> 代替您的 List< T> ,以自动识别添加的新项目。您的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);
    }
}

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

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