动态生成GridView列
-
动态生成GridView列(每次需要绑定的列的数目不同),即动态绑定数据源时列数目不固定的绑定方式
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://www.blogbus.com/flbh-logs/233317059.html想实现这样的功能吗?在程序运行中使GridView动态生成列,而并不是将列固定写死在GridView上
写个绑定GrideView的方法
1 /// <summary> 2 /// 绑定生成GridView 3 /// </summary> 4 /// <param name="gdv">要绑定的GridView</param> 5 /// <param name="dtblDataSource">GridView的数据源</param> 6 /// <param name="strDataKey">GridView的DataKeyNames</param> 7 public static void GridViewBind(GridView gdv, DataTable dtblDataSource, string strDataKey) 8 { 9 gdv.Columns.Clear(); 10 11 gdv.AutoGenerateColumns = false; 12 gdv.DataSource = dtblDataSource; 13 gdv.DataKeyNames = new string[] { strDataKey }; 14 15 for (int i = 0; i < dtblDataSource.Columns.Count; i++) //绑定普通数据列 16 { 17 BoundField bfColumn = new BoundField(); 18 bfColumn.DataField = dtblDataSource.Columns[i].ColumnName; 19 bfColumn.HeaderText = dtblDataSource.Columns[i].Caption; 20 gdv.Columns.Add(bfColumn); 21 } 22 23 gdv.Columns[1].Visible = false; 24 25 CommandField cfModify = new CommandField(); //绑定命令列 26 cfModify.ButtonType = ButtonType.Button; 27 cfModify.SelectText = "修改"; 28 cfModify.ShowSelectButton = true; 29 gdv.Columns.Add(cfModify); 30 31 gdv.DataBind(); 32 }
只要调用这个方法就可以啦!试试吧!
************************************************************************************************
转帖:http://hi.baidu.com/nirvanan/blog/item/4c9ba84a998d7ef883025c1b.html
文件名:list.aspx
前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="List.aspx.cs" Inherits="manager_general_List" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body style="font-size: 12px;"> <form id="form1" runat="server"> <img src="../images/arrow03.gif" /><span style="font-weight: bold"> <asp:Literal ID="ltl_listName" runat="server"></asp:Literal></span><br /> <div style="clear: both; height: 20px; width: 100%;"> </div> </form> </body> </html>
=======================================================================
后台代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 using System.Web.UI; 5 using System.Web.UI.WebControls; 6 7 using System.Data; 8 using System.Data.OleDb; 9 using System.Collections; 10 using System.Drawing; 11 12 public partial class manager_general_List : System.Web.UI.Page 13 { 14 15 GridView gvshow = null;//定义全局变量 16 public static bool sign; 17 18 protected void Page_Load(object sender, EventArgs e) 19 { 20 string tbName = ""; //是要在gridview中显示的数据表名 21 if (Request.QueryString["t"]!=null&&Request.QueryString["t"]!="") 22 { 23 tbName=Request.QueryString["t"].ToString(); 24 } 25 else 26 { 27 common.MsgBox("没有相应的内容!");//此为自定的弹出消息框函数。使用者可自定义。或者去掉。 28 Response.End(); 29 } 30 31 if (sign != null) //根据标记符号来判断,重新绑定那个控件 32 { 33 if (sign ==false) 34 { 35 36 string sql = getListSql(tbName);//获取要在gridview中显示的字段 37 if (sql=="") 38 { 39 common.MsgBox("没有相应的内容!");//此为自定的弹出消息框函数。使用者可自选定义。或者去掉。 40 Response.End(); 41 } 42 try 43 { 44 setBind(sql,tbName); 45 //ltl_listName.Text = common.getFieldValueFromTab("tb_showname", "ctbname", tbName, 0, "cshowname")+"列表"; 46 } 47 catch (System.Exception errr) 48 { 49 common.MsgBox("没有相应的内容!");//此为自定的弹出消息框函数。使用者可自选定义。或者去掉。 50 Response.End(); 51 } 52 53 } 54 55 } 56 57 } 58 59 //获取要在gridview中显示的字段的sql 60 public string getListSql(string tbName) 61 { 62 string sqlStr = ""; 63 string temp = ""; 64 65 //以下tb_listfield 为数据库中保存gridview要列表的其他表的字段名,包含两字段,cname,cfield, 66 //其中cname为要显示的表的表名,cfield为该表要显示的字段名。 67 DataSet ds = common.RunQuery("select * from tb_listfield where cname='" + tbName + "' order by cindex"); 68 if (ds.Tables.Count>0) 69 { 70 foreach (DataRow row in ds.Tables[0].Rows) 71 { 72 temp += row["cfield"].ToString()+","; 73 } 74 } 75 if (temp!="") 76 { 77 temp = temp.Substring(0, temp.Length - 1);//去掉最后一个逗号 78 sqlStr = "select " + temp + " from " + tbName; 79 } 80 return sqlStr; 81 } 82 83 public void setBind(string sql,string tbName) 84 { 85 86 DataTable dt = getDataTable(sql); //获得数据源 87 string headerText = ""; 88 89 gvshow = new GridView();//new一个grideview 90 gvshow.Width = Unit.Pixel(700);//宽度 91 gvshow.AlternatingRowStyle.BackColor =Color.FromArgb(0xF2,0xF2,0xF2);//偶数行的颜色 92 gvshow.HeaderStyle.BackColor = Color.FromArgb(0xF2, 0xF2, 0xF2);//表头的颜色 93 gvshow.HeaderStyle.Font.Bold = true; 94 95 gvshow.AutoGenerateColumns = false;//设置自动产生列为false 96 gvshow.RowEditing += new GridViewEditEventHandler(gvshow_RowEditing); //添加编辑事件 97 gvshow.RowDeleting += new GridViewDeleteEventHandler(gvshow_RowDeleting);//添加删除事件 98 gvshow.DataSource = dt;//设置数据源 99 100 //遍历数据源所有的列,并绑定到gridview 101 for (int i = 0; i < dt.Columns.Count; i++) 102 { 103 BoundField bc = new BoundField(); 104 bc.DataField = dt.Columns[i].ColumnName.ToString(); 105 106 headerText = dt.Columns[i].Caption.ToString(); 107 108 //替换表头文字 109 DataSet hDs=common.RunQuery("select top 1 * from tb_listfield where cname='"+tbName+"' and cfield='"+headerText+"'"); 110 if (hDs.Tables.Count>0) 111 { 112 if (hDs.Tables[0].Rows.Count>0) 113 { 114 headerText = hDs.Tables[0].Rows[0]["cheadertext"].ToString(); 115 } 116 } 117 bc.HeaderText = headerText; 118 119 bc.ItemStyle.HorizontalAlign =HorizontalAlign.Center;//居中对齐 120 gvshow.Columns.Add(bc); 121 } 122 123 //添加编辑列 124 CommandField cf = new CommandField();//命令字段 125 cf.ButtonType = ButtonType.Link;//超链接样式的按钮 126 cf.ShowEditButton = true;//显示编辑按钮 127 cf.CausesValidation = false;//引发数据验证为false 128 cf.HeaderText = "编辑"; 129 cf.ItemStyle.HorizontalAlign = HorizontalAlign.Center; 130 gvshow.Columns.Add(cf);//添加编辑按钮到gridview 131 132 133 //添加删除列 134 CommandField cf2 = new CommandField(); 135 cf2.ButtonType = ButtonType.Link; 136 cf2.ShowDeleteButton = true;//显示删除按钮 137 cf2.CausesValidation = false; 138 cf2.HeaderText = "删除"; 139 cf2.ItemStyle.HorizontalAlign = HorizontalAlign.Center; 140 gvshow.Columns.Add(cf2); 141 142 //添加包复选框的模板列 143 TemplateField tf = new TemplateField(); 144 tf.ItemTemplate = new MyTemplate("", DataControlRowType.DataRow); 145 //tf.HeaderText = "选择"; 146 tf.HeaderTemplate = new MyTemplate("", DataControlRowType.Header); 147 tf.ItemStyle.HorizontalAlign = HorizontalAlign.Center; 148 gvshow.Columns.Add(tf); 149 150 151 152 153 gvshow.DataBind(); 154 155 form1.Controls.Add(gvshow); 156 } 157 158 //删除gridview的行 159 void gvshow_RowDeleting(object sender, GridViewDeleteEventArgs e) 160 { 161 int i = e.RowIndex; 162 Response.Write("delete:" + gvshow.Rows[i].Cells[0].Text.ToString()); 163 } 164 165 166 //编辑行 167 public void gvshow_RowEditing(object sender, GridViewEditEventArgs e) 168 { 169 int i = e.NewEditIndex; 170 string id = gvshow.Rows[i].Cells[0].Text.ToString(); 171 172 Response.Write("you want to edit" + id); 173 } 174 175 176 //获得数据表 177 public DataTable getDataTable(string sql) 178 { 179 DataTable dt = common.RunQuery(sql).Tables[0]; 180 return dt; 181 } 182 183 }
=======================================================================
创建模板列的类文件名:MyTemplate.cs
类代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 5 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8 9 /// <summary> 10 /////添加包复选框的模板列的类 11 /// </summary> 12 public class MyTemplate : ITemplate 13 { 14 private string strColumnName; 15 private DataControlRowType dcrtColumnType; 16 17 public MyTemplate() 18 { 19 // 20 // TODO: 在此处添加构造函数逻辑 21 // 22 } 23 24 /**//// <summary> 25 /// 动态添加模版列 26 /// </summary> 27 /// <param name="strColumnName">列名</param> 28 /// <param name="dcrtColumnType">列的类型</param> 29 public MyTemplate(string strColumnName, DataControlRowType dcrtColumnType) 30 { 31 this.strColumnName = strColumnName; 32 this.dcrtColumnType = dcrtColumnType; 33 } 34 35 public void InstantiateIn(Control ctlContainer) 36 { 37 switch (dcrtColumnType) 38 { 39 case DataControlRowType.Header: //列标题 40 41 //如果头部使用标题则使用以下代码 42 //Literal ltr = new Literal(); 43 //ltr.Text = strColumnName; 44 //ctlContainer.Controls.Add(ltr); 45 46 //头部也创建一个checkbox,则使用如下代码 47 CheckBox cbh = new CheckBox(); 48 cbh.ID = "CheckBox1"; 49 cbh.Checked = false; 50 ctlContainer.Controls.Add(cbh); 51 break; 52 case DataControlRowType.DataRow: //模版列内容——加载CheckBox 53 CheckBox cb = new CheckBox(); 54 cb.ID = "CheckBox1"; 55 cb.Checked = false; 56 ctlContainer.Controls.Add(cb); 57 break; 58 } 59 } 60 61 }
==================================================================
common.cs类代码
1 using System; 2 using System.Collections.Generic; 3 4 using System.Web; 5 6 using System.Data; 7 using System.Data.OleDb; 8 using System.Collections; 9 using System.Drawing; 10 11 using System.Security.Cryptography;//使用md5 12 using System.Text.RegularExpressions;//正则表达式命名空间 13 14 /// <summary> 15 ///common 的摘要说明 16 /// </summary> 17 public class common 18 { 19 20 public common() 21 { 22 // 23 //TODO: 在此处添加构造函数逻辑 24 // 25 } 26 27 28 //获取数据库链接 29 public static OleDbConnection getConn() 30 { 31 string myPath=System.Web.HttpContext.Current.Server.MapPath( "~/ "); 32 myPath+="App_Data\\xxxx.mdb"; 33 return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + myPath + ";Persist Security Info=True"); 34 35 } 36 37 //运行查询 38 public static DataSet RunQuery(String QueryString) 39 { 40 41 // 声明连接字符串。本示例使用oledb 42 //连接到xxxx.mdb数据库 43 44 OleDbConnection DBConnection = common.getConn(); 45 OleDbDataAdapter DBAdapter; 46 DataSet ResultsDataSet = new DataSet(); 47 48 try 49 { 50 51 //运行查询并建立一个数据集 52 DBAdapter = new OleDbDataAdapter(QueryString, DBConnection); 53 DBAdapter.Fill(ResultsDataSet); 54 55 //关闭数据库连接 56 DBConnection.Close(); 57 58 } 59 catch (Exception ex) 60 { 61 62 //如果数据库连接仍然打开则关闭它 63 if (DBConnection.State == ConnectionState.Open) 64 { 65 DBConnection.Close(); 66 } 67 MsgBox("无法连接到数据库!"); 68 System.Web.HttpContext.Current.Response.Write("<script>history.back(1);</script>"); 69 70 } 71 72 return ResultsDataSet; 73 74 } 75 76 //弹出消息框 77 public static void MsgBox(string msg) 78 { 79 System.Web.HttpContext.Current.Response.Write("<script>alert('" + msg + "')</script>"); 80 }