C#动态生成gridview

最近,开发了个项目,提交测试时,测试人员要测试后台录入数据,问题出来了,由于权限限制,不能直接到DB服务器上去查数据【isqlw不能用了,哎】,DBA也不在,其他一切途径似乎都不可行了。哎,命苦啊,只有再开发个web查询页面,在页面中输入select语句,来显示结果集。结果集用什么显示,当然是GridView了。不过结果集可能有多个,怎么全部显示呢,限定结果集为10个,页面中用10个GridView,通过隐藏,来显示?No,这种山寨做法,不是我所能搞不定的,咱来动态生成GridView吧,有几个结果集,就动态生成几个GridView,呵呵,这样多好。很快写下了下面的核心代码:
private void BindData()
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnString"].ToString()))
{
string sql = this.txtSQL.Value.Trim();
SqlDataAdapter myda = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
con.Open();
myda.Fill(ds, "tb");
for (int i = 0; i < ds.Tables.Count; i++)
{
GridView temp = new GridView();
this.Page.Controls.Add(temp);
temp.AutoGenerateColumns = true;
temp.CssClass = "GreenBorderTbl";
temp.HeaderStyle.CssClass="GreenBorderTblTh";
temp.ShowFooter = true;
temp.FooterStyle.CssClass = "Foot";
temp.DataSource = ds.Tables[i];
temp.DataBind();
if (ds.Tables[i].Rows.Count > 0)
{
temp.FooterRow.Cells[0].Text = string.Format("共{0}条记录", ds.Tables[i].Rows.Count);
}
}
con.Close();
}
}
catch (Exception ex)
{
Response.Write(string.Format("BindData:[StackTrace]{0}[Message]{1}", ex.StackTrace, ex.Message));
}
}
运行,my god! 竟然出现了下面的图片:C#动态生成gridview

抓紧看msdn,GridView的构造函数,看到了下面的代码:

CS:

// Add the GridView object to the Controls collection
// of the PlaceHolder control.
GridViewPlaceHolder.Controls.Add(customersGridView);

aspx:

<asp:placeholder id="GridViewPlaceHolder" runat="Server"/>

呵呵,发明创造咱不行,比葫芦画瓢也不行吗?抓紧在aspx中声明:<asp:placeholder id="GridViewPlaceHolder"
runat="Server"/> ,在cs中把this.Page.Controls.Add(temp)替换成this.GridViewPlaceHolder.Controls.Add(temp)。编译运行程序,呵呵,出现了下面的画面: C#动态生成gridview
呵呵,动态生成gridview是达到了,placeholder是什么东东呢,以后再说吧!

keyword: 动态 生成 gridview