将click事件添加到gridview中的动态生成按钮
问题描述:
我正在向gridview onRowDataBound事件添加按钮
I am adding buttons to my gridview onRowDataBound Event
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var firstCell = e.Row.Cells[1];
firstCell.Controls.Clear();
Button btn_Check = new Button();
btn_Check.ID = "btn_Check";
btn_Check.Text = firstCell.Text;
btn_Check.Click += new EventHandler(btn_Check_Click);
firstCell.Controls.Add(btn_Check);
}
}
protected void btn_Check_Click(object sender, EventArgs e)
{
Response.Write("btn_Check_Click event called");
}
但点击按钮后,btn_Check_Click事件永远不会被调用。
如何制作按钮。点击调用btn_Check_Click?
but on clicking the button the btn_Check_Click event is never called.
how to make the button.Click call btn_Check_Click?
答
你应该在RowCreated [ ^ ]事件。这将在DataBinding以及在PostBack上重建页面时创建控件。
试试这个:
You should add dynamic controls in RowCreated[^] event of the GridView. This will create controls at DataBinding and as well as when rebuilding a page on PostBack.
Try this:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var firstCell = e.Row.Cells[1];
firstCell.Controls.Clear();
Button btn_Check = new Button();
btn_Check.ID = "btn_Check";
btn_Check.Text = firstCell.Text;
btn_Check.Click += new EventHandler(btn_Check_Click);
firstCell.Controls.Add(btn_Check);
}
}
protected void btn_Check_Click(object sender, EventArgs e)
{
Response.Write("btn_Check_Click event called");
}
--Amit
--Amit