简体   繁体   中英

Alternative To Adding Multiple Class Items Into Multiple Combo Boxes? C#

I have a Fish class, and I'm trying to display the different species in a combo box, the way I'm currently doing it right now is way too tedious, there has to be a better way.

In 'Species1' you can see me attempting to add the same specie in all 4 combo boxes.

I have 4 combo boxes, and I want to display these 9 fish species in all 4 combo boxes, letting the user choose which 4 species he has caught.

            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());

Start by putting all your species in a list:

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()
}

And then set a copy of the list as the DataSource of all your ComboBox objects:

Catch1ComboBox.DataSource = new BindingList<object>(species);
Catch2ComboBox.DataSource = new BindingList<object>(species);
Catch3ComboBox.DataSource = new BindingList<object>(species);
Catch4ComboBox.DataSource = new BindingList<object>(species);

The use of new BindingList is to prevent all the combo boxes from hooking to the same source and thus being forced to hold the same value.

There is an example of this in the Microsoft documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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