Reputation: 673
Im using c# .net windows form application. I have a database with some tables.I have two comboboxes (A & B). I have populated a combo box A with column names of a table using sys.columns. Now when i select an item in combo box A ,combo box B should be populated with the same items except the selected item which was selected in combobox A .
Upvotes: 0
Views: 217
Reputation: 15794
I'd use a combination of static extension methods and LINQ.
The static extension part would look like this:
// static class...
public static class ComboBoxHelper
{
public static string GetSelectedIndexText(this ComboBox target)
{
return target.Items[target.SelectedIndex].ToString();
}
public static object[] GetNonSelectedItems(this ComboBox target)
{
string selected = GetSelectedIndexText(target);
try
{
object[] result =
target.Items.Cast<object>().Where(c => c.ToString()
!= selected).ToArray();
return result;
}
catch
{
return new object[] { };
}
}
public static void ReplaceItems(this ComboBox target, object[] newRange)
{
target.Items.Clear();
target.Items.AddRange(newRange);
}
}
And the LINQ:
// LINQ:
private void ComboBoxA_SelectedIndexChanged(object sender, EventArgs e)
{
comboBoxB.ReplaceItems(comboBoxA.GetNonSelectedItems());
}
HTH!
Note: there's probably more efficient way than returning an array of list items, but I haven't found this to be a big issue in terms of the big picture (e.g. overall performance, etc).....
Upvotes: 1
Reputation: 13844
m_comboB.Items.AddRange((from item in m_comboA.Items.Cast<object>()
where item != m_comboA.SelectedItem
select item).ToArray());
Or you can use this way which don't remove duplicate items (Sam pointed this out in his comment):
m_comboB.Items.AddRange(Enumerable.Range(0, m_comboA.Items.Count)
.Where(index => index != m_comboA.SelectedIndex)
.Select(index => m_comboA.Items[index]).ToArray());
Upvotes: 0
Reputation: 2421
I think you will have to code the filling/removal of B in the Change Event of A
Upvotes: 0
Reputation: 32936
You should delete either this question or this one which are about identical things. anyway, here is my identical answer:
in the selected item changed event of A, add code which clears B, then loops round each item in A's Item collection and adds it to B as long as the index of the current item is different from the index of the SelectedItem in A.
Something like (pseudo code, not tested)
b.Items.Clear;
for(int i=0; i<A.Items.Count; i++)
{
if (i!=A.SelectedItemIndex)
{
b.Items.Add(A.Items[i]);
}
}
or
B.Items.Clear;
foreach(object o in A.Items)
{
b.Items.Add(o);
}
b.Items.Remove(A.SelectedItem);
should do it as well.
Upvotes: 1