This piece of code
<asp:DropDownList runat="server" ID="testdropdown" SelectedValue="2">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:DropDownList>
yields this error:
The 'SelectedValue' property cannot be set declaratively.
Yet, this is a legal and commonly used edit template for databound GridViews. The SelectedValue
attribute certainly appears to be declaratively set here.
<EditItemTemplate>
<asp:DropDownList runat="server"
ID="GenreDropDownList"
DataSourceID="GenreDataSource"
DataValueField="GenreId"
DataTextField="Name"
SelectedValue='<%# Bind("Genre.GenreId") %>'>
</asp:DropDownList>
</EditItemTemplate>
The question is: what is the difference between the cases when you are allowed to set it declaratively and those in which you are not? The error message implies that it's never allowed.
'DropDownList' has a SelectedValue which is invalid because it does not exist in the list of items. As it is possible for the user to change the values of the list (in a codetable) it is possible that an earlier selected item not exists anymore.
The DropDownList control is a web server element that creates the drop-down menu and lets users select a single item from various options. You can add any number of items to the DropDownList. Almost all web pages contain a drop-down list, but it is mostly present in registration forms or sign-in pages.
in markup use SelectedValue='<%# "32" %>' syntax .(note the order of single and then the double quotes in the following example ):
<asp:DropDownList ID="ddlField" SelectedValue='<%# "32" %>'
runat="server" DataTextField="Name" DataValueField="ID" >
</asp:DropDownList>
or in code-behind just after DataBinding .(example):
ddlField.DataSource = Fields.SelectAll();
ddlField.DataBind();
ddlField.SelectedValue = "32";
It means you cannot set it through the designer.
The correct way is:
<asp:DropDownList runat="server" ID="testdropdown">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2" Selected></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:DropDownList>
The reason the bound method works is because the value isn't selected in design mode but at runtime after the control is bound to a datasource
The DropDownList.SelectedValue method is meant to be applied at runtime hence the error about not being able to set it 'decoratively'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With