使用DataGrid动态绑定DropDownList

使用DataGrid动态绑定DropDownList

 

    简单的使用模板列绑定DropDownList,初学者想必都会了,但有时候,我们要做的就是在编辑的时候想让某一列定制为DropDownList,并且根据正常情况下显示的值自动变换DropDownList中所选的值,然后保存选择后的值到数据库或XML文件,其实要做到这样的功能并不难,只要我们学会使用DataGrid的DataGrid1_ItemDataBound事件就行了,跟我来做个例子。

    //检索数据库的函数
      public DataSet GetZcbd()
      {
        try
       {
        DataSet ds=new DataSet();  
        string searchString="select id,yy,bj from zc";
        da=new OleDbDataAdapter(searchString,conn);
        da.Fill(ds,"yy");   
         return ds;
       }
       catch
       {
        return null;   
       } 
      }


     //绑定DataGrid  
    private void BindGrid()
      {
       DataSet ds = new DataSet();
       ds = us.GetZcbd();
       if (ds!=null)
       {
        this.DataGrid1.DataSource = ds;
        this.DataGrid1.DataBind();
       }
       else
       {
        msg.Alert("加载数据错误!",Page);
       }
      }
   
    绑定好DataGrid以后,设定模板列,让其正常显示下为Label,并绑定为数据库中一ID值,在编辑状态下为DropDownList,并绑定为数据库中一Name值,我们现在要做的就是当我们选择编辑时根据Label的值自动从数据库中取出编号为ID值的姓名,并用DropDownList默认选中。(注释:为了方便大家学习,我给出一个简单代码的例子,供大家参考)

      private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
         if (e.Item.ItemType == ListItemType.EditItem)
         {
             DataRowView drv = (DataRowView)e.Item.DataItem;
          string current = drv["label1"].ToString();
          DropDownList ddl = (DropDownList)e.Item.FindControl("ddl");
          ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(current));
         }
         if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem)) 
     {
          Label t = (System.Web.UI.WebControls.Label)e.Item.FindControl("label1");
          string current = this.BindDDL(int.Parse(t.Text));
          e.Item.Cells[1].Text = current;
         }
        }

        private string BindDDL(int ddd)
        {
         string sss = "";
         if (ddd==1)
         {
          sss="张三";
          return sss;
         }
         else
         {
             sss="李四";
          return sss;
         }
        }

 

   注释:msg为一个类似WinForm的messagebox对话框,不必理会。可以使用label.Text代替
ATR:www.cnblogs.com/hbzxf 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值