[英]Alternative To Adding Multiple Class Items Into Multiple Combo Boxes? C#
我有一條魚 class,我試圖在一個組合框中顯示不同的物種,我現在這樣做的方式太乏味了,必須有更好的方法。
在“Species1”中,您可以看到我試圖在所有 4 個組合框中添加相同的物種。
我有 4 個組合框,我想在所有 4 個組合框中顯示這 9 種魚,讓用戶選擇他捕獲的 4 種。
Species1 = new Fish("Angler",5);
Catch1ComboBox.Items.Add(Species1.Getspecies());
Catch2ComboBox.Items.Add(Species1.Getspecies());
Catch3ComboBox.Items.Add(Species1.Getspecies());
Catch4ComboBox.Items.Add(Species1.Getspecies());
Catch1ComboBox.SelectedIndex = 0;
Species2 = new Fish("Cod", 3);
Catch1ComboBox.Items.Add(Species2.Getspecies());
Species3 = new Fish("Haddock", 4);
Catch1ComboBox.Items.Add(Species3.Getspecies());
Species4 = new Fish("Hake", 1);
Catch1ComboBox.Items.Add(Species4.Getspecies());
Species5 = new Fish("Horse Mackerel", 0.5m);
Catch1ComboBox.Items.Add(Species5.Getspecies());
Species6 = new Fish("Witches", 3);
Catch1ComboBox.Items.Add(Species6.Getspecies());
Species7 = new Fish("Plaice", 8);
Catch1ComboBox.Items.Add(Species7.Getspecies());
Species8 = new Fish("Skate and Rays", 1.8m);
Catch1ComboBox.Items.Add(Species8.Getspecies());
Species9 = new Fish("Whiting", 7);
Catch1ComboBox.Items.Add(Species9.Getspecies());
首先將您的所有物種放在一個列表中:
var species = new List<object> {
new Fish("Angler", 5).GetSpecies(),
new Fish("Cod", 3).GetSpecies(),
new Fish("Haddock", 4).GetSpecies(),
new Fish("Hake", 1).GetSpecies(),
new Fish("Horse Mackerel", 0.5m).GetSpecies(),
new Fish("Witches", 3).GetSpecies(),
new Fish("Plaice", 8).GetSpecies(),
new Fish("Skate and Rays",1.8m).GetSpecies(),
new Fish("Whiting", 7).GetSpecies()
}
然后將列表的副本設置為所有ComboBox
對象的DataSource
:
Catch1ComboBox.DataSource = new BindingList<object>(species);
Catch2ComboBox.DataSource = new BindingList<object>(species);
Catch3ComboBox.DataSource = new BindingList<object>(species);
Catch4ComboBox.DataSource = new BindingList<object>(species);
使用new BindingList
是為了防止所有的組合框掛鈎到同一個源,從而被迫保持相同的值。
Microsoft 文檔中有一個示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.