Dropdownlist populated from datasource - values ar

2019-08-24 13:41发布

问题:

I have an asp dropbox which I populate from database:

this is the aspx

<asp:DropDownList runat="server" ID="ddl_last" AppendDataBoundItems="true">

and this is the cs:

  ddl_last.DataSource = eggsContext.Customers;
        ddl_last.DataValueField = "last_name";
        ddl_last.DataTextField = "last_name";
        ddl_last.DataBind();

When I try to get ddl_last.SelectedValue from the c# code I get nothing. infact ddl_last.Items count is 0! When I don't populate it from code, but write in the aspx

<asp:ListItem Text="example" />

everything works.

I can get the value from javascript by writing document.getElementById('ddl_last').value;

But I was wondering what did microsoft screw up this time that this is not working from the code behind?

回答1:

After seeing your issue in comment, I think this may help you resolve it:

To disable view state for a page and to enable it for a specific control on the page, set the EnableViewState property of the page and the control to true, set the ViewStateMode property of the page to Disabled, and set the ViewStateMode property of the control to Enabled.

http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstatemode.aspx

Note also, with ViewState being disabled, you can still retrieve the posted value by

if (Request["ddl_last"] != null)
    val = Request["ddl_last"];


回答2:

Looking at the issue it seems that when you try to access ddl_last.SelectedValue and ddl_last.Items count your ddl_last list has not been data bound. Make sure you are accessing those values after you have bound data