ASP:DropDownList in ItemTemplate:为什么允许 SelectedValue 属性? [英] ASP:DropDownList in ItemTemplate: Why is SelectedValue attribute allowed?

查看:18
本文介绍了ASP:DropDownList in ItemTemplate:为什么允许 SelectedValue 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码

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

产生此错误:

SelectedValue"属性不能为以声明方式设置.

The 'SelectedValue' property cannot be set declaratively.

然而,这是数据绑定 GridView 的合法且常用的编辑模板.SelectedValue 属性似乎是在此处以声明方式设置的.

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.

推荐答案

在标记中使用 SelectedValue='<%# "32" %>' 语法.(注意下例中单引号和双引号的顺序):

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>

或在 DataBinding 之后的代码隐藏中.(示例):

or in code-behind just after DataBinding .(example):

  ddlField.DataSource = Fields.SelectAll();
  ddlField.DataBind();           
  ddlField.SelectedValue = "32";

这篇关于ASP:DropDownList in ItemTemplate:为什么允许 SelectedValue 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆