Reputation: 155
Sorry if the question is confusing, this is what I wish to do.
I have 4 comboboxes in a winform. All 4 comboboxes have the same information in them (ie Street Addresses)
If in the first combobox I select, for instance, First St - how do I make First St greyed out (or unselectable) in the other comboboxes.
EDIT:
I have the following code which i place in comboBox1_SelectedIndexChanged:
for (int i = 0; i < comboBox2.Items.Count; i++)
{
if (comboBox2.Items[i] == comboBox1.SelectedItem)
{
comboBox2.Items.Remove(comboBox2.Items[i]);
i--;
}
}
}
This works fine for removing the first choice from subsequent comboboxes, however if I accidentally choose the wrong street and then select the correct street from the first comboBox, both streets are removed from the second comboBox
e.g. -> 1st selection Main St oops I mean First St
now I go to the second comboBox and both Main St and First St have been removed. Is the a way around this, or do I have to hope the user will not make a mistake?
Upvotes: 0
Views: 170
Reputation: 32445
Or use approach from another side.
Just check if selected value from second ComboBox
is already selected in another ComboBox controls
string _notSelected = "n/a";
var streets = new[] {_notSelected, "Street One", "Street Two"};
this.comboBox1.DataSource = streets;
this.comboBox2.DataSource = streets;
void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox current = (ComboBox)sender;
if(current.SelectedValue != null)
{
//Here you can compare indexes of all comboboxes or values
if(this.combobox1.SelectedValue != null &&
this.combobox1.SelectedValue.ToString().Equals(current.SelectedValue.ToString())
{
current.SelectedValue = _notSelected;
}
// ...same for other comboboxes...
}
}
Upvotes: 0
Reputation: 8394
For example, if you have comboBox1
and comboBox2
, then you could filter the available options based on previous control's selection.
var data = new[] {"a", "b", "c"};
comboBox1.DataSource = comboBox2.DataSource = data;
comboBox1.SelectedValueChanged += (sender, args) =>
comboBox2.DataSource = data.Where(item =>
!item.Equals(comboBox1.SelectedValue)).ToArray();
Upvotes: 0