So the problem is that items moved from the combobox to the listbox may be duplicates of items already in the listbox. (Right?)
You need to keep track of which items are already in the listbox, independent of the database.
private HashSet<string> SelectedSoftware = new HashSet<string>();
obj.cn.Open();
using (SqlCommand cmd2 = new SqlCommand("Select software from specs where mfcitno='" + label2.Text + "'", obj.cn))
{
using (SqlDataReader dr2 = cmd2.ExecuteReader())
{
while (dr2.Read())
{
ard = dr2["software"].ToString();
}
}
}
obj.cn.Close();
if (ard != null)
{
string[] arr1 = ard.Split(',');
foreach (string item in arr1)
{
listBox1.Items.Add(item);
SelectedSoftware.Add(item);
}
}
Then when selecting from the combobox, check if the item is already in
SelectedSoftware
, and if so, don't add it again. And keep
SelectedSoftware
updated:
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBox4.Text))
{
string sc = comboBox4.SelectedItem.ToString();
if (!SelectedSoftware.Contains(sc))
{
listBox1.Items.Add(sc);
SelectedSoftware.Add(sc);
comboBox4.Items.Remove(comboBox4.SelectedItem);
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string li = listBox1.Text;
comboBox4.Items.Add(li);
listBox1.Items.Remove(li);
SelectedSoftware.Remove(li);
}
Even better, if possible, would be to remove from the combobox the elements that are already in the listbox, as soon as the listbox is loaded, so they cannot be added to the listbox if they are already there. (Imagine the case where the listbox is initially empty and the combobox has all of the possible selections. At any point in the sequence of selections from the combobox or listbox, all of the possible selections are in one or the other control. This is what your code already does, it just doesn't start out that way.) If the user can enter a
new value in the combobox, then you'll need to ensure it isn't a duplicate, as above.
Finally, from your code it appears that simply changing the selected items in the listbox and combobox causes the items to be moved from one to the other. It seems like a better user experience to have a pair of buttons that move the selected items from one list to the other.