【问题标题】:C# add list of strings to combobox and when item is remove automatic affect to listC#将字符串列表添加到组合框,当项目被删除时自动影响到列表
【发布时间】:2023-03-23 22:05:01
【问题描述】:

我想将列表中的所有字符串添加到组合框,并且当从 ui 中删除一项时,希望自动对列表生效(该列表也删除那些选定的字符串)。

解决这类问题的最佳技术是什么。

例子:

List<string> users = new List<string>(){ "frsUser", "secUser", "thrUser", "fouUser" };

private void frmMain_Load(object sender, EventArgs e)
{
    foreach(var user in users)
        cmbUser.Items.Add(user);
}

private void btnRemove_Click(object sender, EventArgs e)
{
    cmbUser.Items.RemoveAt(cmbUser.SelectedIndex);
    // Should it be removed also here? 
    users.RemoveAt(cmbUser.SelectedIndex);
}

【问题讨论】:

    标签: c# list binding combobox dataset


    【解决方案1】:

    这可以使用BindingSource 轻松完成,该BindingSource 处理您的组合框项目集合与列表之间的交互

    private void frmMain_Load(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = users;
        c.DataSource = bs;
    }
    

    现在在按钮单击事件中使用此代码

    private void btnRemove_Click(object sender, EventArgs e)
    {
        if(c.SelectedIndex == -1)
            return;
    
        BindingSource bs = c.DataSource as BindingSource;
        bs.RemoveAt(c.SelectedIndex);
    
        // Just to show the updated list 
        foreach(string u in users)
            Console.WriteLine(u);
    }
    

    【讨论】:

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