简体   繁体   中英

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

I am working on a simple application that to add/delete string/s into an array and show that in ListBox.

显示我的应用的图片

My code shows only the latest value that was typed into the textBox and

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)
{

}

This code makes no sense. You are adding one single item to a list, then convert it to an array (still containg one item) and finally loop through this array, which of course adds one item to the previously cleared listbox. Therefore your listbox will always contain one single item. Why not simply add the item directly?

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

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

Also clear the listbox in Delete_Click instead of Add_Click .


If you prefer to keep the items in a separate collection, use a List<string> , and assign it to the DataSource property of the listbox.

Whenever you want the listbox to be updated, assign it null , then re-assign the list.

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

The problem with code is quite simple. Instead of adding new item to list your code creates new list with one added item only. I am trying to interpret functions of program and they seem to be:

  1. Enter new text into top level text box.
  2. If Add button is clicked your item goes on top of the list (if it's bottom see end of my answer).
  3. If item(s) is selected in list and Delete is clicked selected item(s) is/are deleted.

To achieve this you should first insert text on top of the list by using Add_Click code, than delete selected items using Delete_Click code. There is additional code to guard against inserting empty or white space only strings plus trimming of leading and trailing white 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);
}

To complete adding and deleting logic I would add Delete All button which would just call List.Items.Clear() . If you prefer to add text at the end just use Add method form @Olivier Jacot-Descombes answer.

You can use in 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
        }
    }

and you can use the same method for validate if a value exist when try to add

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM