First you need to understand the flow of
DropDownList[
^]. It contains two important properties:
1.
DataValueField
2.
DataTextField
For the
DataValueField
and
DataTextField
properties, if you only set value to one of them, the other property is also set to the same value. If you only specify
DropDownList1.DataTextField = "CategoryName"
, both the display text and value of each DropDownList item are set to Name. If you only specify
DropDownList1. DataValueField = "CategoryID"
, both the display text and value of each DropDownList item are set to ID.
See this:
<asp:dropdownlist id="DropDownList1" runat="server" xmlns:asp="#unknown">
</asp:dropdownlist>
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=testing;Integrated Security=True;"))
{
SqlCommand cmd = new SqlCommand("select CategoryID,CategoryName from Categories",conn);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryID";
DropDownList1.DataBind();
}
}
--Amit