使用 C# 在 WinForm 中托管的列表框中添加和删除文本

2024-02-19

我正在开发一个简单的应用程序,用于将字符串添加/删除到数组中并在列表框中显示。

我的代码仅显示在文本框中输入的最新值

private void Add_Click(object sender, EventArgs e)
{
    string add = textBox1.Text;
    List<string> ls = new List<string>();
    ls.Add(add);
    String[] terms = ls.ToArray();
    List.Items.Clear();
    foreach (var item in terms)
    {
        List.Items.Add(item);
    }
}


private void Delete_Click(object sender, EventArgs e)
{

}

这段代码没有任何意义。您正在向列表添加一项,然后将其转换为数组(仍包含一项),最后循环该数组,这当然会向之前清除的列表框添加一项。因此,您的列表框将始终包含一项。为什么不直接添加该项目呢?

private void Add_Click(object sender, EventArgs e)
{
    List.Items.Add(textBox1.Text);
}

private void Delete_Click(object sender, EventArgs e)
{
    List.Items.Clear();
}

同时清除列表框Delete_Click代替Add_Click.


如果您希望将项目保留在单独的集合中,请使用List<string>,并将其分配给DataSource列表框的属性。

每当您希望更新列表框时,请分配它null,然后重新分配列表。

private List<string> ls = new List<string>();

private void Add_Click(object sender, EventArgs e)
{
    string add = textBox1.Text;

    // Avoid adding same item twice
    if (!ls.Contains(add)) {
        ls.Add(add);
        RefreshListBox();
    }
}

private void Delete_Click(object sender, EventArgs e)
{
    // Delete the selected items.
    // Delete in reverse order, otherwise the indices of not yet deleted items will change
    // and not reflect the indices returned by SelectedIndices collection anymore.
    for (int i = List.SelectedIndices.Count - 1; i >= 0; i--) { 
        ls.RemoveAt(List.SelectedIndices[i]);
    }
    RefreshListBox();
}

private void RefreshListBox()
{
    List.DataSource = null;
    List.DataSource = ls;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 C# 在 WinForm 中托管的列表框中添加和删除文本 的相关文章

随机推荐