user12325176
user12325176

Reputation:

System.Int32[] in ComboBox

I have a list of object :

class Cylindree
{
    public int NomCylindree;

    public static List<Cylindree> lesCylindreesTwoStroke = new List<Cylindree>()
    {
        new Cylindree() { NomCylindree = 125},
        new Cylindree() { NomCylindree = 144},
        new Cylindree() { NomCylindree = 150},
        new Cylindree() { NomCylindree = 200},
        new Cylindree() { NomCylindree = 250},
        new Cylindree() { NomCylindree = 300}
    };

    public static List<Cylindree> lesCylindreesFourStroke = new List<Cylindree>()
    {
        new Cylindree() { NomCylindree = 250},
        new Cylindree() { NomCylindree = 300},
        new Cylindree() { NomCylindree = 350},
        new Cylindree() { NomCylindree = 400},
        new Cylindree() { NomCylindree = 450},
        new Cylindree() { NomCylindree = 500}
    };

    public Cylindree(int NomCylindree)
    {
        this.NomCylindree = NomCylindree;
    }

    public Cylindree() { }
}

And in my main, this :

private void lesMoteurs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lesMoteurs.Text == "2T")
            {
                lesCylindrees.Items.Add(Cylindree.lesCylindreesTwoStroke.Select(x => x.NomCylindree).ToArray().ToString());
            }
        }

And i got "System.Int32[]" in my ComboBox. I want to get my list in my ComboBox to select the value i want. What i have to do to get my list please ?

Thanks for further help

Upvotes: 0

Views: 79

Answers (2)

Slai
Slai

Reputation: 22866

Another option is to set the values as DataSource :

lesCylindrees.DataSource = Cylindree.lesCylindreesTwoStroke.ConvertAll(x => x.NomCylindree);

or

lesCylindrees.DataSource = Cylindree.lesCylindreesTwoStroke;
lesCylindrees.DisplayMember = "NomCylindree";

Upvotes: 1

Zaelin Goodman
Zaelin Goodman

Reputation: 896

This is quite simple. Ad it stands, you're using linq correctly to create a list of integers, but then the item you're adding to the comboBox is the result of turning that ARRAY into a string. If you want to add each integer to the array, you can do the following:

if (lesMoteurs.Text == "2T") {
    var intArr = Cylindree.lesCylindreesTwoStroke.Select(x => x.NomCylindree).ToArray();
    foreach (int i in intArr) {
        lesCylindrees.Items.Add(i.ToString());
    }
}

Alternately, the Collection does have an AddRange function that accepts an array:

lesCylindrees.Items.AddRange(Cylindree.lesCylindreesTwoStroke.Select(x => x.NomCylindree.ToString()).ToArray());

Upvotes: 0

Related Questions