很多方法可以爲爲下拉式菜單(DropDownList)添加第一個選項,下面是Insus.NET小結了幾個方法,僅供參考:
Html code:
View Code <body><form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
數據源與綁定:
View Code protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
Data_Binding();
}
}
private void Data_Binding()
{
this.DropDownList1.DataSource = Site();
this.DropDownList1.DataTextField = "key";
this.DropDownList1.DataValueField = "value";
this.DropDownList1.DataBind();
}
private Dictionary<string, string> Site()
{
Dictionary<string, string> site = new Dictionary<string, string>();
site.Add("Insus.NET cnblogs", "http://insus.cnblogs.com");
site.Add("Microsoft", "http://www.microsoft.com");
site.Add("Google", "http://www.google.com");
return site;
}
以下所有方法,均以以上html或code作變動。
第一種,修改Html Code,把DropDownList屬性AppendDataBoundItems的值設爲true,然後直接添加一個item:<asp:ListItem Text="--選擇--" Value=""></asp:ListItem> 在DropDownList內。
View Code <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"><asp:ListItem Text="--選擇--" Value=""></asp:ListItem>
</asp:DropDownList>
第二種方法,Html Code無需更改,
View Code <asp:DropDownList ID="DropDownList1" runat="server" ></asp:DropDownList>
修改Data_Binding()方法,如下:
View Code private void Data_Binding(){
this.DropDownList1.DataSource = Site();
this.DropDownList1.DataTextField = "key";
this.DropDownList1.DataValueField = "value";
this.DropDownList1.DataBind();
//添加下面代碼:
DropDownList1.Items.Insert(0, new ListItem( "--選擇--",""));
}
第三種方法:
Html改爲如下,設置AppendDataBoundItems屬性與及實現OnDataBound事件:
View Code <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" OnDataBound="DropDownList1_DataBound" ></asp:DropDownList>
cs code:
View Code protected void DropDownList1_DataBound(object sender, EventArgs e){
DropDownList ddl = (DropDownList)sender;
ddl.Items.Insert(0, new ListItem("--選擇--", "0"));
}