DropDownList loses value for data binding
I have the following DropDownList
<asp:DropDownList ID="ddlStartMonth" runat="server" /> And I set the DataSource as follows:
ListItemCollection items = new ListItemCollection(); items.Add(new ListItem("January", "1")); items.Add(new ListItem("February", "2")); items.Add(new ListItem("March", "3")); items.Add(new ListItem("April", "4")); items.Add(new ListItem("May", "5")); items.Add(new ListItem("June", "6")); items.Add(new ListItem("July", "7")); items.Add(new ListItem("August", "8")); items.Add(new ListItem("September", "9")); items.Add(new ListItem("October", "10")); items.Add(new ListItem("November", "11")); items.Add(new ListItem("December", "12")); ddlStartMonth.DataSource = items; ddlStartMonth.DataBind(); As soon as I call DataBind() , each value of the element is overwritten with its text value (for example, a pair of text values ββ("January", "1") becomes ("January", "January"). So, if I did something like
int month = 1; ddlStartMonth.SelectedValue = month.ToString(); January will be the selected item in the DropDownList, but the operation is ignored instead, and the DropDownList supports the previously selected value. I have to skip something here ... Any ideas?
Note These values ββmust be created programmatically.
Try setting the DataTextField and DataValueField :
ListItemCollection items = new ListItemCollection(); items.Add(new ListItem("January", "1")); items.Add(new ListItem("February", "2")); items.Add(new ListItem("March", "3")); items.Add(new ListItem("April", "4")); items.Add(new ListItem("May", "5")); items.Add(new ListItem("June", "6")); items.Add(new ListItem("July", "7")); items.Add(new ListItem("August", "8")); items.Add(new ListItem("September", "9")); items.Add(new ListItem("October", "10")); items.Add(new ListItem("November", "11")); items.Add(new ListItem("December", "12")); ddlStartMonth.DataSource = items; ddlStartMonth.DataTextField = "Text"; ddlStartMonth.DataValueField = "Value"; ddlStartMonth.DataBind(); Or you can also set them declaratively:
<asp:DropDownList ID="ddlStartMonth" DataTextField="Text" DataValueField="Value" runat="server" /