使用 C# 添加和删除文本 to/from 托管在 WinForm 中的 ListBox

Add and delete text to/from ListBox hosted in WinForm using C#

我正在开发一个简单的应用程序,将 add/delete string/s 放入数组并在 ListBox 中显示。

我的代码只显示输入到文本框中的最新值,

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

代码的问题很简单。您的代码不会添加新项目来列出您的代码,而是创建仅包含一个添加项目的新列表。我正在尝试解释程序的功能,它们似乎是:

  1. 在顶级文本框中输入新文本。
  2. 如果单击 添加 按钮,您的项目将位于列表顶部(如果它位于底部,请参阅我的回答结尾)。
  3. 如果在列表中选择了项目并且单击了删除,则选择的项目is/are 已删除。

为此,您应该首先使用 Add_Click 代码在列表顶部插入文本,然后使用 Delete_Click 代码删除选定的项目。有额外的代码来防止插入空或白色 space 只有字符串加上前导和尾随白色的修剪 space.

private void Add_Click(object sender, EventArgs e)
{
    // Since you do not want to add empty or null
    // strings check for it and skip adding if check fails
    if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text)
    {
        // Good habit is to remove trailing and leading 
        // white space what Trim() method does
        List.Items.Insert(0, textBox1.Text.Trim());
    }
}

private void Delete_Click(object sender, EventArgs e)
{
    // Get all selected items indices first
    var selectedIndices = List.SelectedIndices;

    // Remove every selected item using it's index
    foreach(int i in selectedIndices)
        List.Items.RemoveAt(i);
}

为了完成添加和删除逻辑,我将添加“删除所有”按钮,它只会调用 List.Items.Clear()。如果您更喜欢在末尾添加文本,只需使用添加方法表单@Olivier Jacot-Descombes answer。

您可以在 C# 中使用:

    private void Delete_Click(object sender, EventArgs e)
    {
        if(myList.Contains(textbox1.value))//if your list containt the delete value
        {
           myList.Remove(textbox1.value); //delete this value
        }
        else
        {
           //the list not containt this value
        }
    }

并且您可以使用相同的方法在尝试添加时验证值是否存在

private void AddItem()
{
    if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text))
    {
        var newItem = textBox1.Text.Trim();
        if (!List.Items.Contains(newItem))
        {
            List.Items.Add(newItem);
            // Alternative if you want the item at the top of the list instead of the bottom
            //List.Items.Insert(0, newItem);

            //Prepare to enter another item
            textBox1.Text = String.Empty;
            textBox1.Focus();
        }    
    }
}

private void Add_Click(object sender, EventArgs e)
{
    AddItem();
}

Private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        AddItem();
    }
}  

private void Delete_Click(object sender, EventArgs e)
{
    // Remove every selected item using it's index
    foreach(var item in List.SelectedItems)
    {
        List.Items.Remove(item);
    }
}