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

烂漫一生 提交于 2021-02-08 19:37:40

问题


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

An image that shows my app

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

}

回答1:


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



回答2:


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.




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/46898313/add-and-delete-text-to-from-listbox-hosted-in-winform-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!