简体   繁体   中英

c# dropdownlist avoid multiple insert statements?

This is c# code:

DropDownList ddl;
ddl.Items.Insert(0, new ListItem("--Select Me--", "0"));
ddl.Items.Insert(1, new ListItem("I'm the first", "1"));
ddl.Items.Insert(2, new ListItem("I'm the second", "2"));
ddl.Items.Insert(3, new ListItem("I'm the third", "3"));

Is there a way we can avoid these sequential insert into dropdownlist and bulk insert these values?

You can do this:

DropDownList ddl;
var ls=new List<KeyValuePair<int,string>>()
{
    new KeyValuePair<int,string>(0,"--Select Me--"),
    new KeyValuePair<int,string>(1,"I'm the first"),
    new KeyValuePair<int,string>(2,"I'm the second"),
    new KeyValuePair<int,string>(3,"I'm the third"),
};
ddl.DataTextField="Value";
ddl.DataValueField="Key";
ddl.DataSource=ls;
ddl.DataBind();

Use the AddRange method:

DropDownList ddl;
ddl.Items.AddRange(new ListItem[] { new ListItem ("--Select Me--", "0"), new ListItem("I'm the first", "1"), new ListItem("I'm the second", "2"), new ListItem("I'm the third", "3")});

This might be helpful:

List<ListItem> items = new List<ListItem>();
  items.Add(new ListItem("Alabama", "Alabama"));
  items.Add(new ListItem("Alaska", "Alaska"));
  DropDownList1.Items.AddRange(items.ToArray());
DropDownList ddl = new DropDownList();
ddl.Items.AddRange(new[]
{
    new ListItem("--Select Me--", "0"),
    new ListItem("I'm the first", "1"),
    new ListItem("I'm the second", "2"),
    new ListItem("I'm the third", "3")
});

try this

ddl.Items.Add(new ListItem("--Select Me--", "0"));
ddl.Items.Add(new ListItem("I'm the first", "1"));
ddl.Items.Add(new ListItem("I'm the second", "2"));
ddl.Items.Add(new ListItem("I'm the third", "3"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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