繁体   English   中英

将多个 Class 项目添加到多个组合框中的替代方法? C#

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM