And I set ...">

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.

+6
source share
2 answers

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" / 
+11
source

You need to create a list of ddlStartMonth elements every time every time the page loops (i.e., bootstrap as well as postback).

The right place for this is OnInit () - not PageLoad () - as this prevents putting all this data into the Viewstate

-1
source

Source: https://habr.com/ru/post/958163/


All Articles