Below is a repro for a bug that I came across while reviewing some code.
aspx page:
<asp:DropDownList ID="ddlMain" runat="server" Visible="False" />
<asp:Button ID="btnSelect" runat="server" Text="Select" />
Code behind file:
protected void Page_Load(object sender, EventArgs e)
{
ddlMain.SelectedIndex = 0;
}
Note that ddlMain has visible=False
. On page load if I assign selectedIndex = 0; the selectedIndex value doesn't change and remain -1.
the button is there to enable postback; on postback the above statement fails and the following exception is raised:
'ddlMain' has a SelectedIndex which is invalid because it does not exist in the list of items. Parameter name: value
Why didn't the exception get raised the first time around? And why does it get raised after postback?
I noticed that even though the rendersize for the dropdown is 0; there are still 12 bytes assigned in viewstate - though i couldn't verify what exactly was stored for the control. If i disable viewstate then the exception doesn't get raised after postback.