asp.net – ASP:ItemTemplate中的DropDownList:为什么允许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>

产生此错误

The ‘SelectedValue’ property cannot be
set declaratively.

然而,这是一个合法且常用的数据绑定GridView的编辑模板. SelectedValue属性当然似乎在这里声明性地设置.

<EditItemTemplate>
    <asp:DropDownList runat="server" 
        ID="GenreDropDownList"
        DataSourceID="GenreDataSource" 
        DataValueField="GenreId"
        DataTextField="Name"
        SelectedValue='<%# Bind("Genre.GenreId") %>'>
    </asp:DropDownList>
</EditItemTemplate>

问题是:当你被允许声明性地设置它们和你不属性的情况之间有什么区别?错误信息意味着它不会被允许.

解决方法

这意味着您无法通过设计器进行设置.

正确的方法是:

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

绑定方法的工作原因是因为在设计模式中未选择值,而是在控件绑定到数据源之后的运行时

DropDownList.SelectedValue方法意在在运行时应用,因此无法将其设置为“装饰性”的错误

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....