我有一个正常加载的DataBound DropDownList,但是我想插入另一个显示“--Select--”的项目,而不是自动显示第一个DataBound项目。
有一种简单的方法可以做到这一点,还是我需要手动添加虚拟物品?
这是我的代码:
MyContext fc = new MyContext ();
ddl.DataSource = fc.SomeTable;
ddl.DataBind();
答案 0 :(得分:4)
或者,在标记中添加默认项,并将“AppendDataBoundItems”属性设置为true。
<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="" Text="---Please Select---"></asp:ListItem>
</asp:DropDownList>
答案 1 :(得分:2)
执行数据绑定后执行:
ddl.Items.Insert(0, "---Select---");
这会将其添加为列表中的第一项。
或者,您可以添加新的ListItem而不是字符串,因此您可以使用实际值而不是字符串作为下拉列表值。
所以你可以这样做:
ddl.Items.Insert(0, new ListItem("---Select---", Guid.Empty.ToString());