Reputation: 563
I've got a ComboBox in ComboBoxStyle.DropDownList style.
This gets dynamically created based on the number of a passed paremeter. The letters is an ArrayList of letters which are added to the dropdown
for (int a = i; a < drivesLetters.Count; a++) //drivesLetters {"A", "K", "M", so on so forth}
{
combobox.Items.Add(drivesLetters[a]); //add driveletters at element i to the combobox
}
I've been trying to create a method so that when I click on a dropdown list, the letters which are already selected on other dropdown lists should not show up from the selections. Like on the image above, If I click on M, then M should not show up in the dropdowns which have currently A and K selected. If I select V, then V should be selected, not show on the list, M should be added.
My goal is for each of the ComboBox to have a unique Value. It is to prevent users from choosing the same letter "A" to two ComboBox.
I'm not sure how to actually do this. I wonder if I should have two ArrayLists (one holds the letters used in the dropdown, and another one to hold all the unused letters).
I am looking at an implementation like this (in javascript) but obviously in C#.
Please kindly point me to a good starting point. I've tried so many methods, but no success..
Thanks!
Upvotes: 1
Views: 295
Reputation: 70671
I think something like this should accomplish your goal:
private void comboBox_SelectedItemChanged(object sender, EventArgs e)
{
ComboBox[] comboBoxes = { comboBox1, comboBox2, comboBox3 };
ComboBox senderBox = (ComboBox)sender;
char senderSelection = (char)senderBox.SelectedItem;
foreach (ComboBox comboBox in comboBoxes)
{
if (comboBox != senderBox)
{
char comboBoxSelection = (char)comboBox.SelectedItem;
comboBox.Items.Clear();
comboBox.Items.AddRange(_driveLetters.Where(
letter => letter != senderSelection).Cast<object>().ToArray());
comboBox.SelectedItem = comboBoxSelection;
}
}
}
...where the code assumes your ComboBoxes are named comboBox1, comboBox2, and comboBox3 and _driveLetters
is an instance member IEnumerable<char>
(e.g. List, char[], etc.) that holds the valid drive letters to display. This one event handler would be assigned to the SelectedItemChanged event on all three ComboBoxes.
Obviously you'd adjust the variable names and types to suit your specific purposes. Also, I apologize in advance for any typos and compiler errors. I just typed that here, without compiling or testing. I assume it's close enough to something usable to get you going. :)
Upvotes: 2