sadis
sadis

Reputation: 63

2D array to populate combobox

I am trying to populate a combobox from 2D array. I want it the first dimension to be assigned as DisplayMember values, and the second as ValueMemeber. Have been looking online, but I could not find a solution that would work for me. Below is the code that I am trying to use. This does not work.

string[,] Options = new string[3, 2]{
        {"Invoice", "3"},
        {"Group Invoice", "4"},
        {"Group Invoice BUCKS", "5"} };

cboOption.DataSource = Options;

I have tried using a for loop and it does not work either and I get this error message: "Items collection cannot be modified when the DataSource property is set." Example below:

string[,] Options = new string[3, 2]{
        {"Invoice", "3"},
        {"Group Invoice", "4"},
        {"Group Invoice BUCKS", "5"} };

cboOption.DisplayMember = "Text";
cboOption.ValueMember = "Key";

for (int i = 0; i < Options.GetLength(0); i++)
{
    cboOption.Items.Add(new { Text = Options[i, 0], Key=Convert.ToInt16(Options[i, 1]) });
}

Can I do that? If I can could you give me an example.

Thank you

Upvotes: 0

Views: 2399

Answers (3)

sadis
sadis

Reputation: 63

Thanks to @gmiley for the advise. After trying all the different options came up with a solution.

So I created a class Options instead of the array

    public class Options
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }

Then I used the code below to populate combobox

        var items = new List<Options>
        {
            new Options() { Name="Invoice", Value=3},
            new Options() { Name="Group Invoice", Value=4},
            new Options() { Name="Group Invoice BUCKS", Value=5},
        };

        cboOption.DataSource = items;
        cboOption.DisplayMember = "Name";
        cboOption.ValueMember = "Value";

Upvotes: 0

Lidaranis
Lidaranis

Reputation: 785

Are you sure you have tried this?.. this is a paste straight from vs and it's working

    private void button1_Click(object sender, EventArgs e)
    {
        string[,] Options = new string[3, 2]{
        {"Invoice", "3"},
        {"Group Invoice", "4"},
        {"Group Invoice BUCKS", "5"} };



        for (int i = 0; i < Options.GetLength(0); i++)
        {
            cboOption.Items.Add(new { Text = Options[i, 0], Key = Convert.ToInt16(Options[i, 1]) });
        }

        cboOption.DisplayMember = "Text";
        cboOption.ValueMember = "Key";
    }

Upvotes: 3

gmiley
gmiley

Reputation: 6604

When you have a control databound, you do not add items to the control, you add them to the bound datasource. Instead of adding items to cboOption.Items, add them to the collection that your control is bound to. In your case however, you have an array. You would be better off rewriting that array into a resizable collection or datatable.

Upvotes: 0

Related Questions