views:

4299

answers:

3

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.

+2  A: 

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'

Gautam
That would answer my question, if it weren't for the second part of my question. Clearly, in certain cases, you are allowed to declaratively set SelectedValue, as I illustrated. I am trying to understand the difference between the cases when you are allowed and not.
recursive
Because in the gridview template you haven't actually set a value yet using the bind method. The bind actually happens at runtime.It's like saying "At runtime, when I bind data to it, select a value based on this field"
Gautam
A: 

Then How I show the value in dropdownlist from database in edit mode. it may vary. But you have selected it previously.

+1  A: 

thanks, or hard coding like

 <asp:DropDownList BackColor="#FFFFC0" ID="ddlFeild" runat="server" Width="180px"
  DataTextField="Name" DataValueField="ID"  SelectedValue='<%# "32" %>'>
  </asp:DropDownList>

or in code-behind just after binding, like:

        clsFeilds feilds = new clsFeilds();
        ddlFeild.DataSource = feilds.SelectAll(Session["culture"].ToString());
        ddlFeild.DataBind();
        ddlFeild.Items.Insert(0, new ListItem("Select", ""));
        ddlFeild.SelectedValue = "32";
imanabidi