Setup
Using: Visual Web Developer 2010 Express.
Language: C#.
Target Framework: .NET Framework 4.
ViewState: I have disabled ViewState in the Web.Config - i.e. <configuration><system.web><pages enableViewState="false" />
.
Problem
I have an ASP.NET page with a standard DropDownList control.
I have set EnableViewState="true" and ViewStateMode="Enabled" on the DropDownList.
I'm using data binding in the code-behind to populate the control (this works fine).
Data binding happens in a call from Page_PreRender, on both initial load and post-back.
In a call from a Button Click event handler (i.e. before the Page_PreRender) I am trying to read from the SelectedValue property of the DropDownList.
The problem is: all I ever receive is a zero-length-string ("") value and inspection of the object indicates the control contains to values.
Solution
Ensure EnableViewState="true" is set within the <%@ Page %> directive on the page containing the DropDownList.
Alternatively, you could create an extension method for the DropDownList that reads the value from the HttpRequest collection.
e.g.
public static string GetSelectedValue(this System.Web.UI.WebControls.DropDownList listBox)
{
return HttpContext.Current.Request[listBox.ClientID];
}