CSDN博客

img hbzxf

使用DataGrid动态绑定DropDownList

发表于2004/5/31 11:39:00  7300人阅读

分类: ASP.NET DATAGRID

使用DataGrid动态绑定DropDownList

hbzxf (阿好)
http://www.cnblogs.com/hbzxf

        简单的使用模板列绑定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代替

代码很乱,敬请谅解!

2004.4.2

0 0

相关博文

我的热门文章

img
取 消
img