使用C#向WinForm中托管的ListBox添加文本或从中删除文本 [英] Add and delete text to/from ListBox hosted in WinForm using C#

查看:102
本文介绍了使用C#向WinForm中托管的ListBox添加文本或从中删除文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的应用程序,该程序可将字符串添加/删除到数组中并在ListBox中显示.

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

我的代码仅显示在textBox和

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

还清除 Delete_Click 中的列表框,而不是 Add_Click .

Also clear the listbox in Delete_Click instead of Add_Click.

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

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.

每当要更新列表框时,将其分配为 null ,然后重新分配该列表.

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

这篇关于使用C#向WinForm中托管的ListBox添加文本或从中删除文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆