chikun
chikun

Reputation: 209

adding a item in listBox

My requirement is if an item(text from textBox) already present in the listbox then simply don't add.But the else part I can't use in my foreach loop to add item.here is my code.Help me how I can add an item if a item is not present in the listbox.

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

            }

        }

    }

Upvotes: 1

Views: 119

Answers (3)

chikun
chikun

Reputation: 209

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

    }

here is my solution

Upvotes: 0

kaliba
kaliba

Reputation: 230

If you are using the Listbox from System.Windows.Controls, Quentin Roger already gave you the right solution. I just tried it out to see why it isn't working. You can simply test it in another project:

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

b will be true.

Sorry, I know this should be in a comment and not in a separate answer, but I don't have the privilege to write comments.

Upvotes: 0

Quentin Roger
Quentin Roger

Reputation: 6538

Simply :

ListItem item = new ListItem(TextBox1.Text);

if (!ListBox1.Items.Contains(item))
{
//Add item here
}

Upvotes: 2

Related Questions