[英]How to add a default “Select” option to this ASP.NET DropDownList control?
我是ASP.NET的新开发人员,正在尝试学习Linq-To-Entities。 我试图将一个DropDownList与Linq语句绑定,以获取状态实体中的状态列表。 一切正常。 但是,我现在正在尝试向DropDownList添加“选择”选项,但是它对我不起作用。 你能告诉我如何解决这个问题吗?
ASP.NET代码:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
代码隐藏:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Add(new ListItem("Select", "0", true));
bindStatusDropDownList();
}
}
private void bindStatusDropDownList()
{
Status status = new Status();
DropDownList1.DataSource = status.getData();
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Description";
DropDownList1.DataBind();
}
更新:
我也尝试在DropDownList的标记集中执行此操作,但它对我也不起作用
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
</asp:DropDownList>
它不起作用的原因是,您要向列表中添加一个项目,然后使用新的DataSource
覆盖整个列表,该DataSource
将清除并重新填充列表,从而丢失第一个手动添加的项目。
因此,您需要像这样反向进行操作:
Status status = new Status();
DropDownList1.DataSource = status.getData();
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Description";
DropDownList1.DataBind();
// Then add your first item
DropDownList1.Items.Insert(0, "Select");
尽管这是一个很老的问题,但是另一种方法是更改AppendDataBoundItems属性。 因此,代码将是:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AppendDataBoundItems="True">
<asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
</asp:DropDownList>
我尝试了以下代码。 对我来说很好
ManageOrder Order = new ManageOrder();
Organization.DataSource = Order.getAllOrganization(Session["userID"].ToString());
Organization.DataValueField = "OrganisationID";
Organization.DataTextField = "OrganisationName";
Organization.DataBind();
Organization.Items.Insert(0, new ListItem("Select Organisation", "0"));
移动DropDownList1.Items.Add(new ListItem(“ Select”,“ 0”,true)); 在bindStatusDropDownList()之后;
所以:
if (!IsPostBack)
{
bindStatusDropDownList(); //first create structure
DropDownList1.Items.Add(new ListItem("Select", "0", true)); // after add item
}
如果您执行“添加”,它将添加到列表的底部。 如果要将项目添加到列表的顶部,则需要执行“插入”。
Private Sub YourWebPage_PreRenderComplete(sender As Object, e As EventArgs) Handles Me.PreRenderComplete
If Not IsPostBack Then
DropDownList1.Items.Insert(0, "Select")
End If
End Sub
如果要使第一项变为不可选择,请尝试以下操作:
DropDownList1.Items.Insert(0, new ListItem("Select", "-1"));
DropDownList1.Items[0].Attributes.Add("disabled", "disabled");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.