Retriving data from database and Add Items to DropDownList uisng C#
Suppose I created a table name as ddltable,and I have two columns in that table.column names are id and name.I inserted some values in a ddltable.Now I want to retrive a id column values and display in dropdownlist.
We can do this one in two ways.
1)by using DataReader
2)by using DataSet;
Method I : SqlConnection conn = new SqlConnection(" your connection string ");
conn.Open();
SqlCommand cmd = new SqlCommand("select id from ddltable ", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList2.Items.Add(dr["id"].ToString ());
}
Method II: SqlConnection conn = new SqlConnection(" your connection string ");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from ddltable ", conn);
DataSet ds = new DataSet();
da.Fill(ds, " ddltable ");
DropDownList1.DataSource = ds.Tables["ddltable "].DefaultView ;
DropDownList1.DataTextField = "id";
DropDownList1.DataBind();
Data Binding The following controls are list controls which support data binding:
asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp:Listbox