我使用下面的代码从后面的代码中添加Button到GridView的Cell,但是当我点击我添加的每个按钮时,点击事件(lnk_Click)没有调用,按钮隐藏后我点击它。我可以解决这个问题?
//aspx
<asp:GridView ID="GridView1" runat="server" GridLines="None" Width="940px"
OnSelectedIndexChanged="grid_SelectedIndexChanged"
onrowdatabound="GridView1_RowDataBound" AutoGenerateColumns="False" CssClass="gridview">
<Columns>
<asp:TemplateField HeaderText="...">
<ItemTemplate>
<asp:Panel ID="pnlSteps" runat="server"></asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//Code behind
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Panel pnl = (Panel)GridView1.Rows[i].Cells[0].FindControl("pnlSteps");
LinkButton lnk = new LinkButton();
lnk.Text = "...";
pnl.Controls.Add(lnk);
lnk.Click += new EventHandler(lnk_Click);
}//for
...
protected void lnk_Click(object sender, EventArgs e)
{
//...
}
//修改
我用以下代码填充gridview
//dsSet is DataSet that i fill it with data from Database
DataTable dtt = new DataTable();
dtt.Columns.Add(new DataColumn("status", typeof(string)));
dtt.Columns.Add(new DataColumn("finantial", typeof(string)));
dtt.Columns.Add(new DataColumn("phone", typeof(string)));
dtt.Columns.Add(new DataColumn("name", typeof(string)));
dtt.Columns.Add(new DataColumn("code", typeof(string)));
for (int i = 0; i < dsSet.Tables[0].Rows.Count; i++)
{
DataRow dr = dtt.NewRow();
dr[0]=...;
dr[1]=...;
dr[2]=...;
dr[3]=...;
dr[4]=...;
dtt.Rows.Add(dr);
}//for
GridView1.DataSource = dtt;
GridView1.DataBind();
答案 0 :(得分:1)
因为该按钮位于gridview
内,因此您无法在onclick
中获取其点击事件,但您必须使用GridView.RowCommand并在按钮中使用commandname
< / p>
修改强>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="commandName"
Text="command" />
</ItemTemplate>
</asp:TemplateField>
代码背后的代码:
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "commandName")
{
// add your code
}
}