为下拉式菜单 DropDownList 添加第一个选项

               

很多方法可以为为下拉式菜单(DropDownList)添加第一个选项,下面是Insus.NET小结了几个方法,仅供参考:

Html code:

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内。

  < asp:DropDownList  ID ="DropDownList1"  runat ="server"  AppendDataBoundItems ="true" >    
         < asp:ListItem  Text ="--选择--"  Value ="" ></ asp:ListItem >        
         </ asp:DropDownList >

 

第二种方法,Html Code无需更改,

  < asp:DropDownList  ID ="DropDownList1"  runat ="server"   >                  
         </ asp:DropDownList >

 

修改Data_Binding()方法,如下: 

复制代码
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事件:

< asp:DropDownList  ID ="DropDownList1"  runat ="server"  AppendDataBoundItems ="true"  OnDataBound ="DropDownList1_DataBound"   >                  
         </ asp:DropDownList >

 

cs code:

  protected  void DropDownList1_DataBound( object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        ddl.Items.Insert( 0,  new ListItem( " --选择-- ",  " 0 "));
    }
           
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值