Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a DropDownList with a List Array (c#)

I everyone,

I want to populate a dropdownlist with an List Array.

I have an list with 2 arrays inside, and i want to put the first array in DataTextField and the second one in DataValueField.

I have this:

List<String>[] listWAraay= new List<String>[2];
            listWAraay[0] = new List<String>();
            listWAraay[1] = new List<String>();

Then i'm doing this:

                    ddl.DataSource = listWAraay;
                ddl.DataTextField = listWAraay[0].ToString();
                ddl.DataValueField = listWAraay[1].ToString();
                ddl.DataBind();

Is not supose to work in this way?

like image 214
Miguel Dias Avatar asked Jul 01 '26 12:07

Miguel Dias


1 Answers

You have this;

        List<String>[] listWAraay= new List<String>[2];
        listWAraay[0] = new List<String>();
        listWAraay[1] = new List<String>();

ListWArraList<String>[] listWAraay= new List<String>[2]; contains 2 arrays.

and you separate them into new arrays like this;

        listWAraay[0] = new List<String>();
        listWAraay[1] = new List<String>();

This only now gives you two arrays. which means for you to be able to use them, you have to get the data out of each one.

In your case, you seem to want to get data out at the same time so a simple solution could be;

        foreach(string item in listWAraay[0].zip(listWAraay[1], Tuple.Create))
        {
                ddl.DataTextField = item.item1.ToString();
                ddl.DataValueField = item.item2.ToString();
        }
        
    

supposing both arrays have the same count, you could do;

    for(int 1 = 0; i < listWAraay[0].Count; i++)
    {
            ddl.DataTextField = listWAraay[0][i].ToString();
            ddl.DataValueField = listWAraay[1][i].ToString();
    }
    

Let me know how these work for you.

like image 81
mw509 Avatar answered Jul 04 '26 03:07

mw509