动态生成GridView时,加入DataKeyNames属性,回调时出错解决方法
早上看到有位同学问关于自动生成GridVie并且添加DataKeyNames属性后
回调页面时,出现错误异常.下面是我实现的方法。注意一点。就是数据绑定的时间。
要是先绑定,再添加到div1中,回调页面时,就会出错。
页面代码:
<div runat="server" id="div1" enableviewstate="false">
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
cs代码:
protected void Page_Load(object sender, EventArgs e)
{
bindGV();
}
private static DataTable NewMethod()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["id"] = i;
dr["name"] = "Name" + i;
dt.Rows.Add(dr);
}
return dt;
}
private void bindGV()
{
div1.Controls.Clear();
int t = 0;
while (t < 3)
{
GridView gv = new GridView();
gv = CreateSuperGrid();
div1.Controls.Add(gv);
t++;
}
for (int i = 0; i < div1.Controls.Count;i++ )
{
//我这里是先把GridView加入div1中,之后才进行数据绑定
((GridView)div1.Controls[i]).DataSource = NewMethod();
((GridView)div1.Controls[i]).DataBind();
}
}
private GridView CreateSuperGrid()
{
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.EnableViewState = true;
gv.DataKeyNames = new string[] { "id" };
BoundField bf = new BoundField();
bf = new BoundField();
bf.HeaderText = "序号";
bf.DataField = "id";
gv.Columns.Add(bf);
BoundField bf2 = new BoundField();
bf2.HeaderText = "名称";
bf2.DataField = "name";
gv.Columns.Add(bf2);
CommandField cf = new CommandField();
cf.ShowSelectButton = true;
gv.Columns.Add(cf);
gv.SelectedIndexChanging += new GridViewSelectEventHandler(GridView1_SelectedIndexChanged);
return gv;
}
//用做回调页面用的
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
{
string value = ((System.Web.UI.WebControls.GridView)(sender)).DataKeys[e.NewSelectedIndex].Value.ToString();//这里可以看到取到的id值
}