下拉框绑定数据后如何再加入一项(比如,--请选择--)

本文介绍两种在ASP.NET中为已绑定数据的下拉框添加默认选项的方法。第一种方法是在后台代码中使用Insert方法添加,第二种方法是通过设置AppendDataBoundItems属性并在前台直接定义默认项。

下拉框绑定数据后如何再加入一项

我这有两种方法  一种是从后台加,还有一种是从前台加

  一 是从后台加入 方法如下

前台下拉框:

      <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="False" AppendDataBoundItems="True">
               </asp:DropDownList>

后台绑定代码

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlmessage();
                this.DropDownList1.Items.Insert(0, "--请选择--");
            }

        }
        protected void ddlmessage()
        {
            string strcon = @"data source=PWGO7I3HGBSSP5C\SQLEXPRESS; database=test;Persist Security Info=true;User Id=sa;Password=123;";
            SqlConnection sqlcnn = new SqlConnection(strcon);
            SqlCommand sqlcmm = sqlcnn.CreateCommand();
            sqlcmm.CommandText = "select * from ddl";
            SqlDataAdapter da = new SqlDataAdapter(sqlcmm);
            DataSet dt = new DataSet();
            da.Fill(dt);
            this.DropDownList1.DataSource = dt.Tables[0];
            this.DropDownList1.DataTextField = "Role";
            this.DropDownList1.DataValueField = "Id";
            this.DropDownList1.DataBind();
            //this.DropDownList1.Items.Insert(0, "--请选择--");
      
        }

二 ,第二种方法就需要改dropdownlist 的一个属性了!

      方法如下;<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="False" AppendDataBoundItems="True">
        <asp:ListItem Text="--请选择--" Value="0"></asp:ListItem>
        </asp:DropDownList>

在绑定好数据后,直接这样给下拉框添加项,你在运行的时候是不会起到作用的,所以我们需要修改一个属性

 AppendDataBoundItems=true;             

这样的话,我们想要加的数据就能显示出来了!

 

后台:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlmessage();
             }

        }
        protected void ddlmessage()
        {
            string strcon = @"data source=PWGO7I3HGBSSP5C\SQLEXPRESS; d

 

atabase=test;Persist Security Info=true;User Id=sa;Password=123;";
            SqlConnection sqlcnn = new SqlConnection(strcon);
            SqlCommand sqlcmm = sqlcnn.CreateCommand();
            sqlcmm.CommandText = "select * from ddl";
            SqlDataAdapter da = new SqlDataAdapter(sqlcmm);
            DataSet dt = new DataSet();
            da.Fill(dt);
            this.DropDownList1.DataSource = dt.Tables[0];
            this.DropDownList1.DataTextField = "Role";
            this.DropDownList1.DataValueField = "Id";
            this.DropDownList1.DataBind();
                
        }

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值