I’ve read a few different examples of this, and it seems to be a clear newbie question for those that don’t fully understand the asp.net page life cycle, sorry still learning. None of my attempts to fix have panned out.
aspx:
...
<%
for( int j = 0; j < 11; j++)
{
ChildWeightPounds.Items.Add( new ListItem(j.ToString(),j.ToString()));
}
%>
<asp:DropDownList ID="ChildWeightPounds" runat="server" OnSelectedIndexChanged="DropDownListSelected">
<asp:ListItem Value="">-Select-</asp:ListItem>
</asp:DropDownList>
...
<asp:Button ID="InsertButton" runat="server" Text="Submit" OnClick="InsertButton_Click" />
aspx.cs:
protected void InsertButton_Click(object sender, EventArgs e)
{
foreach (Control c in NewPatientForm.Controls)
{
....
if (c is TextBox)
{
TextBox tb = (TextBox)c;
//Expected response:
Response.Write( "field: " + tb.ID + " = " + tb.Text + "<br />");
}
if (c is DropDownList)
{
DropDownList ddl = (DropDownList)c;
//Unexpected response:
//this is not giving me my selected value, but only the top item ("--select--")
Response.Write("field: " + ddl.ID + ", selectedItem: " + ddl.SelectedItem.Value + "<br />");
}
}
}
It’s pretty clear this is a IsPostBack, DataBind(), problem with my lack of understanding of the page life cycle. But what doesn’t make sense, is i’m iterating through all controls, and textboxes, checkboxes, checkboxlists all work fine, and give me the value in the field, for some reason the dropdownlist doesn’t give me the value.
I’ve tried using the OnSelectedIndexChanged event, I’ve tried using the DataBind() function, but playing with these, still hasn’t gotten me the value.
The biggest issue with your example is you are using inline C# within your page with
<% %>. This isn’t advised forasp.net. That’s more of a legacy/classic ASP approach which won’t play well with .NET for many reasons.Try moving your code that adds the items to the
dropdownlistfrom the markup file into the .cs file, and be sure to hook into a page event that happens at or beforeOnPreRender. That is the last point you can alter the page controls and have viewstate/lifecycle work correctly.It’s likely without running your example that the values are being inserted into the
dropdownlistat the incorrect time in thelifecycle, and because of that when you try to access the selected value in the code behind it doesn’t work.Consider the following article on asp.net lifecycle which may assist you.