DropDownList SelectedValue Problems

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Forget about the controlParameter for the moment, for testing purposes i have
created the following

Markup:

<asp:Table ID="tblSelectRoute" runat="server" CssClass="asp-table">
<asp:TableRow>
<asp:TableCell CssClass="asp-table-header">Select
Route<asp:Label ID="lblTest" runat="server"></asp:Label>
</asp:TableCell>
<asp:TableCell CssClass="asp-table-cells">
<asp:DropDownList ID="DDLSelectRoute" runat="server"
AutoPostBack="True" DataSourceID="SDSRoutesList" DataTextField="Route"
DataValueField="RouteID" CausesValidation="True"
OnSelectedIndexChanged="DDLSelectRoute_SelectedIndexChanged">
</asp:DropDownList>
</asp:TableCell>
</asp:TableRow>
</asp:Table>

Code in the PageLoad event handler:

lblTest.Text = DDLSelectRoute.SelectedValue;

For some reason i cannot fathom, the label control is blank untill the value
in the DDL is changed. The HTML rendered to the browser shows thus

<select name="ctl00$ContentPlaceHolder1$DDLSelectRoute"
onchange="javascript:setTimeout('WebForm_DoPostBackWithOptions(new
WebForm_PostBackOptions("ctl00$ContentPlaceHolder1$DDLSelectRoute", "", true,
"", "", false, true))', 0)" id="ctl00_ContentPlaceHolder1_DDLSelectRoute">
<option selected="selected" value="1">1 - Test</option>
<option value="2">2 - Test</option>

<option value="3">3 - Test</option>

So the first item is selected.

If i add DDLSelectRoute.SelectedIndex = 4; at the begining of the pageload
event handler then the selected index is chyanged but the label control is
still blank until i change the value in the DDL.

If i replace lblTest.Text = DDLSelectRoute.SelectedValue; with lblTest.Text
= DDLSelectRoute.SelectedItem.Value; i get an "Object reference not set to an
instance of an object" exception. But if i then cut lblTest.Text =
DDLSelectRoute.SelectedItem.Value; from the page load event and then paste it
inro the SelectedIndexChanged event handler for the DDL as soon as you change
the DDL then the label control is updated.

I am totally puzzled, it is acting as if the SelectedValue is not set until
you change the DDL at least once.
 
Ignore the above post, the problem was cause by the fact that the
DropDownList ahnd't been data bound yet during the PageLoad event.
 
Back
Top