Reputation: 73
I have two programmatic created combo boxes below. Both share the same items. The items consist of Apple, Banana, Watermelon.
How can I make item unique such that
Scenario 1. Upon "Apple" selected from ComboBox 1, ComboBox 2 will not shows "Apple".
Scenario 2. Upon "Banana" selected from ComboBox 2, ComboBox 1 will not shows "Banana"
In additional, this is done in C# using a Winform application.
for (int i = 0; i < 2; i++)
{
ComboBox cb = new ComboBox();
cb.Items.Add("Apple");
cb.Items.Add("Banana");
cb.Items.Add("Watermelon");
cb.Name = "ComboBox" + i.ToString();
cb.SelectedIndexChanged += new EventHandler((object sender, EventArgs e) =>
{
for (int a = 0; a < 2; a++)
{
ComboBox sequenceUpdate = (ComboBox)flowLayoutPanelA.Controls.Find(i, true)[0];
}
});
flowLayoutPanelA.Controls.Add(cb);
}
Upvotes: 1
Views: 168
Reputation: 1480
You should define a Fruit
class and define its collection for reusability, maybe even a repository. I just wrote in the simplest way and the blocks below fill the bill for now.
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
_fruits = new List<Fruit>{
new Fruit(0, "--Choose--"),
new Fruit(1, "Apple"),
new Fruit(2, "Banana"),
new Fruit(3, "Watermelon"),
};
LoadComponent(comboBox1, _fruits);
}
private readonly IEnumerable<Fruit> _fruits;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
LoadComponent(comboBox2, comboBox1.SelectedIndex == 0
? null
: _fruits.Where(x => x.Id != Convert.ToInt32(comboBox1.SelectedValue)).ToList());
}
private void LoadComponent(ListControl control, IEnumerable<Fruit> source) {
control.DataSource = source;
control.ValueMember = "Id";
control.DisplayMember = "Name";
}
}
class Fruit {
public Fruit(int id, string name) {
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
Upvotes: 1
Reputation: 8991
Without any code in the question it's impossible to give you an answer that will work with your project.
However in general terms, you could populate the second box's values using the .OnChanged event from the first using something like this:
IList<string> boxASource = new List<string> { "Apple", "Banana", "Watermelon" };
string selectedValueA = boxASource[0];
IList<string> boxBSource = boxASource.Where(x => !x.Equals(selectedValueA)).ToList();
Upvotes: 0