Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDownList losing value on databind

Tags:

c#

asp.net

I have the following DropDownList

<asp:DropDownList ID="ddlStartMonth" runat="server" />

And I'm setting 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 item's value is overwritten by its text value (e.g. the text-value pair ("January", "1") becomes ("January", "January"). So, if I were to do something like

int month = 1;
ddlStartMonth.SelectedValue = month.ToString();

"January" would be the selected item in the DropDownList, but instead, the operation is ignored, and the DropDownList maintains the previously selected value. I must be missing something here... Any ideas?

Note: These values need to be created programmatically.

like image 783
Mr Jones Avatar asked Nov 15 '13 19:11

Mr Jones


1 Answers

Try setting the DataTextField and DataValueField properties:

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 set them declaratively as well:

<asp:DropDownList ID="ddlStartMonth" DataTextField="Text" DataValueField="Value" runat="server" /
like image 141
KodeKreachor Avatar answered Oct 31 '22 14:10

KodeKreachor