简体   繁体   English

asp.net下拉列表

[英]asp.net dropdownlist

i am adding items to dropdownlist using addrange method, here is my code 我正在使用addrange方法将项目添加到dropdownlist中,这是我的代码

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 但这给了我错误,因为无法隐式转换字符串ti listitem

please give me a solution 请给我一个解决方案

thanks in advance sangita 在此先感谢sangita

You need to create new ListItems 您需要创建新的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, 您还将需要引用System.Linq,

Kindness, 善良,

Dan

I tried Dan's example, but had to add .ToArray() to get it to work, ie: 我尝试了Dan的示例,但是必须添加.ToArray()使其起作用,即:

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());
   object []cou = new object[]{"India",
                               "United States",
                               "United Kingdom",
                               "Canada",
                               "Singapore",
                               "Australia",
                               "Sudia Arabia",
                               "South Africa" };
    dpcountry.Items.AddRange(cou);

You are creating an array of type ListItem, but you are trying to add strings to this array. 您正在创建类型为ListItem的数组,但是您正在尝试向该数组添加字符串。 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 */ };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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