thiru
thiru

Reputation: 39

how to set datasource to dropdownlist

I want to add a datasource to a dropdownlist. This dropdownlist is one of the columns of a gridview. Here I want to add a datasource to the dropdownlist dynamically without using the sqldatasource.

(vs2008 and c#)

Upvotes: 0

Views: 15401

Answers (3)

Kasrak
Kasrak

Reputation: 1561

Here is the codes you are looking for

Example 1 :

public enum Color
{
    RED,
    GREEN,
    BLUE
}

Every Enum type derives from System.Enum. There are two static methods that help bind data to a drop-down list control (and retrieve the value). These are Enum.GetNames and Enum.Parse. Using GetNames, you are able to bind to your drop-down list control as follows:

protected System.Web.UI.WebControls.DropDownList ddColor;

private void Page_Load(object sender, System.EventArgs e)
{
     if(!IsPostBack)
     {
        ddColor.DataSource = Enum.GetNames(typeof(Color));
        ddColor.DataBind();
     }
}

Example 2 :

List<Person> myPList = new List<Person>();



Person p1 = new Person();

p1.ID = 1;

p1.Name = "Bob";

p1.Color = "Blue";



Person p2 = new Person();

p2.ID = 2;

p2.Name = "Joe";

p2.Color = "Green";



myPList.Add(p1);

myPList.Add(p2);



this.DropDownList1.DataSource = myPList;

this.DropDownList1.DataTextField = "Color";

this.DropDownList1.DataValueField = "ID";

this.DropDownList1.DataBind();  

for a more complete practice look at here : https://stackoverflow.com/a/9076237/132239

also don't forget always to mark your answers as an answer

Upvotes: 0

Meetu Choudhary
Meetu Choudhary

Reputation: 1355

yes as it is in the itemtemplate so you wont get it directly for that you have to use findcontrol

Upvotes: 1

Kelsey
Kelsey

Reputation: 47766

You could implement the OnDataBinding event for the dropdownlist control in your grid. In the event you could assign the DataSource property and other attributes to whatever you like. Bind it to a List<YourObject> even.

Doing it on the OnDataBinding event also allows you to customize the values in the ddl on the fly as well. So each row's ddl could have a different set of options available based on some other data in your row if you need that type of functionality.

Tons of flexability with the ASP.NET controls if the OnDataBinding method is used instead of the auto (easy mode) wire ups.

Upvotes: 1

Related Questions