Friday, October 17, 2008

Populate data in dropdown in asp.net

Populate data in dropdown in asp.net:

C# Code:
using System.Data;
using System.Data.SqlClient;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection("Server=localhost;database=test;uid=sa;pwd="); SqlDataAdapter da = new SqlDataAdapter("Select ID,productName from Products", cn); DataSet ds = new DataSet();
try
{
da.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "productName";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cn.Close();
da.Dispose();
ds.Dispose();
}
}
}