简体   繁体   English

C#表单-复选框

[英]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. 当用户选中该复选框时,它将在列表框中添加“ Anchovies”。 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"). 我不想发生的是,当用户取消选择复选框并再次选择它时,“ Anchovies”再次添加到列表框中(显示了两个“ 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);
                }            
        }

The key is to check if Anchovies already exists on the listBox1 items. 关键是检查listBox1项上是否已经存在Anchovies

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

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

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. 要解决此问题,您需要在列表框中插入任何值之前,请选中您的列表框(该值是否已经存在)。

eg 例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM