Reputation:
I use below code for add Button to GridView's Cell from code behind,but when i click on each button that i add,the click event(lnk_Click) doesn't call and button hides after i click on it.how can i solve this problem?
//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)
{
//...
}
//Edit
I fill the gridview with below code
//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();
Upvotes: 3
Views: 888
Reputation: 5475
because the button is inside the gridview
so you can't get its click event in onclick
but you have to use GridView.RowCommand and use commandname
in the button
Edit
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="commandName"
Text="command" />
</ItemTemplate>
</asp:TemplateField>
code behind:
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "commandName")
{
// add your code
}
}
Upvotes: 1