ASP:DropDownList in ItemTemplate: Why is SelectedValue attribute allowed?

recursive picture recursive · Feb 24, 2009 · Viewed 30.2k times · Source

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.

Answer

Iman picture Iman · Mar 13, 2010

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";