Monday, May 3, 2010

How to bind Dropdownlist in asp.net

In this article I am going to show that how we can fetch data in a DropDownList from Sql server. Here I used a DropDownList in which on the load of form the Name value will come from a stored procedure.

In fetching data from database in a DropDownList we have to set a property of DropDownList like as.

DroplistData.DataTextField = "Name";

Sample Code (C#)

string connString =ConfigurationManager.

ConnectionStrings["connectionstring"].ToString()

SqlConnection con = new SqlConnection(connString);

con.Open();

SqlCommand cmd = new SqlCommand();

cmd.Connection = con;

cmd.CommandText = "spChGetNames";

cmd.CommandType = CommandType.StoredProcedure;

DataSet ds = new DataSet();

SqlDataAdapter da = new SqlDataAdapter();

da.SelectCommand = cmd;

da.Fill(ds);

DropDownList1.DataSource = ds;

DropDownList1.DataTextField = "Name";

DropDownList1.DataValueField = "ID";

DropDownList1.DataBind();

No comments: