Jennie
Jennie

Reputation: 45

asp.net dropdownlist

i am adding items to dropdownlist using addrange method, here is my code

ListItem[] cou =
new ListItem[8]{"India",
                "United States",
                "United Kingdom",
                "Canada",
                "Singapore",
                "Australia",
                "Sudia Arabia",
                "South Africa" };
dpcountry.Items.AddRange(cou);

but it gives me error as cannot implicitly convert string ti listitem

please give me a solution

thanks in advance sangita

Upvotes: 0

Views: 1123

Answers (4)

CodePoet
CodePoet

Reputation:

I tried Dan's example, but had to add .ToArray() to get it to work, ie:

string[] cou =new string[8]{
              "India",
              "United States",
              "United Kingdom",
              "Canada",
              "Singapore",
              "Australia",
              "Saudi Arabia",
              "South Africa" };

dpcountry.Items.AddRange(cou.Select(c => new ListItem(c)).ToArray());

Upvotes: 2

Daniel Elliott
Daniel Elliott

Reputation: 22887

You need to create new ListItems

try

string[] cou =new string[8]{
              "India",
              "United States",
              "United Kingdom",
              "Canada",
              "Singapore",
              "Australia",
              "Sudia Arabia",
              "South Africa" };
dpcountry.Items.AddRange(cou.Select(c => new ListItem(c));

You will need a reference to System.Linq too,

Kindness,

Dan

Upvotes: 3

Razzie
Razzie

Reputation: 31232

You are creating an array of type ListItem, but you are trying to add strings to this array. That is why you get this error. To get this code to work, you should change it to:

new ListItem[8]{ new ListItem("India"), new ListItem("United"), /* etcetera */ };

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94653

   object []cou = new object[]{"India",
                               "United States",
                               "United Kingdom",
                               "Canada",
                               "Singapore",
                               "Australia",
                               "Sudia Arabia",
                               "South Africa" };
    dpcountry.Items.AddRange(cou);

Upvotes: 1

Related Questions