【问题标题】:C# Correct Way of Binding a List to a ListBoxC#将列表绑定到ListBox的正确方法
【发布时间】:2015-08-27 02:03:15
【问题描述】:

假设我有以下代码:

        private List<Employee> displayEmp;

        public Form1()
        {
            InitializeComponent();
            displayEmp = new List<Employee>();
        }

在我的添加按钮处理程序中:

   private void button1_Click(object sender, EventArgs e)
        {
            string[] selection = comboEmail.GetItemText(comboEmail.SelectedItem).Split(',');

            Employee add = new Employee(Convert.ToInt32(selection[0]), selection[1], selection[2], selection[3]);

            if (!(comboEmail.SelectedIndex == 0))
            {

                if(!(listEmail.Items.Contains(add))){

                      displayEmp.Add(add);;
                      listEmail.DataSource = null;
                      listEmail.DataSource = displayEmp;
                }
                else
                {
                    MessageBox.Show(add.ToString() + " Already Added.");
                }

            }

        }

我的删除按钮处理程序:

private void button2_Click(object sender, EventArgs e)
{

    int indexRemoval = listEmail.SelectedIndex;

    if (indexRemoval != -1)
    {
        displayEmp.RemoveAt(indexRemoval);
        listEmail.DataSource = null;
        listEmail.DataSource = displayEmp;
    }

}

I have a list of employees in a ComboBox that when selected, I add to a listbox.在我的添加/删除按钮处理程序中,我做对了吗?当您将集合绑定到控件并且想要添加/删除项目时,正确的做法是什么?

【问题讨论】:

    标签: c# forms button listbox


    【解决方案1】:

    通常的做法是使用ObservableCollection&lt;T&gt; 而不是List&lt;T&gt;

        private ObservableCollection<Employee> displayEmp;
    
        public Form1()
        {
            InitializeComponent();
            displayEmp = new ObservableCollection<Employee>();
            // you need to assign DataSource only once
            listEmail.DataSource = displayEmp;
        }
    

    ObservableCollection 实现了INotifyCollectionChanged 接口,该接口通知 ListView 集合中的所有更改(添加和删除项目)。 由于 ObservableCollection 通知更改,您不需要强制刷新绑定,因此不需要

        listEmail.DataSource = null;
        listEmail.DataSource = displayEmp;
    

    【讨论】:

      【解决方案2】:

      是的,您的收藏绑定正确。

      我也会这样做:

      listEmail.DisplayMember = "Name";
      

      Name 是您希望在列表框中显示的 'Employee' 中的任何属性,否则它将尝试将对象转换为字符串。

      【讨论】:

        猜你喜欢
        • 2011-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多