[英]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.