ListBox.Contains not working properly

I have 2 errors in my code and cannot figure out how to solve this.

This is my code:

private void add_button_Click(object sender, EventArgs e)` { try { if (list_selected.Contains(List_selection.SelectedItem)) { MessageBox.Show("Can't add the same type twice"); } else { list_selected.Items.Add(List_selection.SelectedItem); } } catch { { MessageBox.Show("No type selected"); } } } 

These are the errors:

Error 1

The best overloaded method match for 'System.Windows.Forms.Control.Contains (System.Windows.Forms.Control)' has some invalid arguments

Error 2

Argument 1: cannot be converted from 'object' to 'System.Windows.Forms.Control' C: \ Projects \ flashloader2013 \ mainapplication \ Form1.cs 467 44

Please help me. ]

List_selection and list_selected are ListBoxes .

+4
source share
5 answers

You need to write:

 if (list_selected.Items.Contains(List_selection.SelectedItem)) 

Otherwise, you check the collection of listView / Listbox controls (any control that may contain other controls)

+3
source

Instead of ListBox.Contains , which checks whether the control contains the child control that you want to check whether the ListBox contains this element. So use ListBox.Items.Contains :

 if (list_selected.Items.Contains(List_selection.SelectedItem)) 
+3
source

Turn this:

 if (list_selected.Contains(List_selection.SelectedItem)) 

in

 if (list_selected.Items.Contains(List_selection.SelectedItem)) 
+2
source

Your code should look like this

 private void button1_Click(object sender, EventArgs e) { if (listBox1.Items.Contains(listBox1.SelectedItem)) { MessageBox.Show("Can't add the same type twice"); } else { listBox1.Items.Add(listBox1.SelectedItem); } } 
+1
source

Your code will not work because you are trying to query a ListBox.

If you see your add

 list_selected.Items.Add(List_selection.SelectedItem); 

You will see that you need to request items. as shown below.

 list_selected.Items.Contains(List_selection.SelectedItem)) 
+1
source

Source: https://habr.com/ru/post/1486191/


All Articles