我有一个 DropDownList
与 aspx 页面中的 DataSource
关联。加载页面时,我需要再添加一项。
我的代码:
<asp:LabelDropDownList ID="ddlVisualTemplate" runat="server" LabelText="Visual Template:" DataSourceID="VisualTemplateDataSource" DataTextField="Name" DataValueField="Id" AutoPostBack="true" OnSelectedIndexChanged="ddlVisualTemplate_SelectedIndexChanged"/>
<asp:EntityDataSource ID="VisualTemplateDataSource" runat="server"
ConnectionString="name=Entities"
DefaultContainerName="Entities" EnableFlattening="False"
EntitySetName="tbEmailVisualTemplates">
我正在尝试添加一个额外的项目:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlVisualTemplate.Items.Add(new ListItem("None", string.Empty));
}
}
如果我调试代码,它会通过它。但是当页面显示时,下拉列表不包含 "None"
。
最佳答案
对于原始发布者来说可能为时已晚,但可能对其他用户有用:
您可以在设计器(或代码)中添加值“None”、“Choose value”等,并通过设置 AppendDataBoundItems="防止
。这将使 DataBind
覆盖它真”DataBind
追加而不是清除。
以下示例来自 Scott Guthrie 的帖子 ListControl.AppendDataBoundItems Property in ASP.NET 2.0 .
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource1" DataTextField="state" DataValueField="state">
<asp:ListItem Text="(Select a State)" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
SelectCommand="SELECT DISTINCT [state] FROM [authors]">
</asp:SqlDataSource>
关于c# - 下拉列表数据源并从 C# 添加额外项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6541645/