在listBox中添加项目

本文关键字:项目 添加 listBox | 更新日期: 2023-09-27 18:27:55

我的要求是,如果列表框中已经存在一个项目(textBox中的文本),那么就不要添加。但我不能在foreach循环中使用其他部分来添加项。这是我的代码。如果列表框中没有项目,请帮助我如何添加项目。

protected void Button1_Click(object sender, EventArgs e)
{
      if (RadioButton1.Checked)
      {
            if (ListBox1.Items.Count == 0)
            {
                ListBox1.Items.Add(TextBox1.Text);
                Label2.Text = "<b style='color:green'> item updated in the listbox </b>";
            }
            else 
            {
                foreach (ListItem li in ListBox1.Items)
                {
                    if (li.Text.ToUpper() == TextBox1.Text.ToUpper())
                    {
                        Label2.Text = "<b style='color:red'> access denied 
                        break;
                    }
                }
            }
        }
    }

在listBox中添加项目

简单地说:

ListItem item = new ListItem(TextBox1.Text);
if (!ListBox1.Items.Contains(item))
{
//Add item here
}

如果您正在使用System.Windows.Controls中的Listbox,Quentin Roger已经为您提供了正确的解决方案。我只是试着看看为什么它不起作用。你可以简单地在另一个项目中测试它:

ListBox lb = new ListBox();
lb.Items.Add("Test");
bool b = lb.Items.Contains("Test");

b将是真的。

对不起,我知道这应该在评论中,而不是单独回答,但是我没有写评论的特权。

    bool status = false;
  if (RadioButton1.Checked)
    {
        if (ListBox1.Items.Count == 0)
        {
            ListBox1.Items.Add(TextBox1.Text);
            Label2.Text = "<b style='color:green'> item updated in the listbox </b>";
        }
        else 
        {
            foreach (ListItem li in ListBox1.Items)
            {
                if (li.Text.ToUpper() == TextBox1.Text.ToUpper())
                {
                    Label2.Text = "<b style='color:red'> access denied </b>";
                    status = true;
                    break;
                }
            }
            //ListItem item = new ListItem(TextBox1.Text);
            //if (!ListBox1.Items.Contains(item))
            //{
            //    ListBox1.Items.Add(TextBox1.Text);
            //    Label2.Text = "<b style='color:green'> item updated in the listbox </b>";
            //}
            if (status == false)
            {
                ListBox1.Items.Add(TextBox1.Text);
                Label2.Text = "<b style='color:green'> item updated in the listbox </b>";
            }
        }
    }

这是我的解决方案