簡體   English   中英

C#將字符串列表添加到組合框,並且在刪除項目時自動影響列表

[英]C# add list of strings to combobox and when item is remove automatic affect to list

我想將列表中的所有字符串添加到組合框,並且當從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);
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM