Quigg15405
Quigg15405

Reputation: 121

C# form - Checkboxes

I'm wondering how to restrict my checkbox from adding to my listbox. At the moment when the user checks the checkbox it will add "Anchovies" to the listbox. What I don't want to happen is when the user deselects the checkbox and re selects it again, "Anchovies" is added to the listbox again (showing two lots of "Anchovies").

private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {           
                if (checkBox1.Checked)
                 {
                     listBox1.Items.Add("Anchovies");
                     double total = Convert.ToDouble(textBox2.Text);
                     total = total + .5;
                     textBox2.Text = Convert.ToString(total);
                }            
        }

Upvotes: 1

Views: 163

Answers (3)

Waqas Ali
Waqas Ali

Reputation: 1519

To fix this issue, you need to check your list box(for this value, either it is already there or not) before inserting any value in it.

e.g

foreach (var item in listBox1.Items )
{
  if(item.ToString() != "Anchovies")
  {
    listBox1.Items.Add("Anchovies");
  }
  // other code here.
}

Upvotes: 0

bash.d
bash.d

Reputation: 13207

Do it this way

if (checkBox1.Checked)
             {
                 if(!listBox1.Items.Contains("Anchovies"))
                     listBox1.Items.Add("Anchovies");
                 double total = Convert.ToDouble(textBox2.Text);
                 total = total + .5;
                 textBox2.Text = Convert.ToString(total);
            }      

Upvotes: 3

Oscar Mederos
Oscar Mederos

Reputation: 29813

The key is to check if Anchovies already exists on the listBox1 items.

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{           
        if (checkBox1.Checked)
         {
             //If the item is already there, we don't do anything.
             if (!listBox1.Items.Contains("Anchovies")) {
                 listBox1.Items.Add("Anchovies");
                 double total = Convert.ToDouble(textBox2.Text);
                 total = total + .5;
                 textBox2.Text = Convert.ToString(total);
             }
        }            
}

Upvotes: 3

Related Questions