C# .NET - creating a DropDownList programatically

Asked By Johan Ee on 12-Dec-05 10:15 AM
Hello,

I want to create a DropDownList in a special way.. 
If some condition I want the list to have one extra item. The items are "hard coded", not from any data source. I guess one way of doing it would be to create it programatically... but I'm not sure how to create list items one by one...

Does anybody have any ideas?

thnx!

DropDownList - Asked By F Cali on 12-Dec-05 10:24 AM

Hi Johan,

To add items in your drop down list programmatically with hard-coded values, simply call the Add method of the Items property of the DropDownList:

DropDownList1.Items.Add(new ListItem("Alpha", "A"));
DropDownList1.Items.Add(new ListItem("Bravo", "B"));

Something like this - Asked By Aarthi Saravanakumar on 12-Dec-05 10:27 AM

If this is from a Database..and you have a DataSet..
you can bind the DataSet..then use
List.Items.Add(new ListItem("Select One"));

ok thanks :) - Asked By Johan Ee on 12-Dec-05 11:06 AM

not so difficult maybe :)
Simpler Way - Asked By F Cali on 12-Dec-05 11:10 AM
Hi Johan,

Yes, it's not that difficult.  Actually there's even an easier way to do it.  If the Text displayed in your drop down list will be the same as the value that you will assign to it, then it will look like this:

DropDownList1.Items.Add("Alpha"); 
DropDownList1.Items.Add("Beta");
You can use the - Asked By Jon Wojtowicz on 12-Dec-05 11:29 AM
hard coded list in your aspx and simply add the new item to the list. If you need the new item at a certain position you can use the Insert method. An example would be to add a new item, "Select An Item", to the beginning of the list

DropDownList1.Items.Insert(0, "Select An Item");

OR

DropDownList1.Items.Insert(0, new ListItem( "Select An Item"));