1

When a user clicks a checkbox it adds the item to the listbox, and when the user unchecks it, it must be removed from the list. I'm trying to use the FindByText method but it doesn't seem to appear in my visual studio. Here's my current work:

 if (checkBox1.Checked == true)
 {
        listBox1.Items.Add(checkBox1.Text);
 }
 else
 {
        listBox1.Items.Remove(listBox1.Items.FindByText(checkBox1.Text));
 }
Mayank Patel
  • 3,868
  • 10
  • 36
  • 59
Karl
  • 11
  • 1
  • 1
    I haven't used winforms in a long time, but judging by your code you're adding a string, and then trying to remove a control. Are you sure it shouldn't simply be: `listBox1.Items.Remove(checkBox1.Text)` – Rob Dec 11 '15 at 15:41

2 Answers2

0

You add String so you should remove String as well; so you have no need in any FindByText:

listBox1.Items.Remove(checkBox1.Text);

Complete fragment:

if (checkBox1.Checked) // "== true" is redundant
  listBox1.Items.Add(checkBox1.Text);
else
  listBox1.Items.Remove(checkBox1.Text);

or even

  // To prevent double adding
  listBox1.Items.Remove(checkBox1.Text);

  if (checkBox1.Checked)
    listBox1.Items.Add(checkBox1.Text);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

to find an item by text in listbox you would have to iterate through all the items
refer to this article about removing items from listbox : C# removing items from listbox

Community
  • 1
  • 1
SyMo7amed
  • 368
  • 2
  • 15