I had a problem trying to add a button to my grid. My GridView is first loaded with data in the PageLoad event.
Then I take the data in the first cell of each row and create a button that will link to the URL. To get the url, I have to execute a query with the data in the first cell as a parameter. At first I did this in the RowDataBound event, but defeating this query for each row made it very slow.
So, I decided to add a button that will retrieve the URL only when you click the button.
Here is my gridview:
<asp:GridView ID="gvResults" runat="server"
OnRowDataBound="gvResults_RowDataBound"
OnRowCommand="gvResults_RowCommand">
</asp:GridView>
And my code is:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
LinkButton lb = new LinkButton();
lb.CommandArgument = e.Row.Cells[0].Text;
lb.CommandName = "NumClick";
lb.Text = e.Row.Cells[0].Text;
e.Row.Cells[0].Controls.Add((Control)lb);
}
}
protected void gvResults_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "numclick":
string url = GetUrl(e.CommandArgument.ToString());
Response.Redirect(url);
break;
default:
break;
}
}
The grid generates a fine; a button is added to the grid for each row. But when I click on it, the RowCommand event does not fire, and the page just refreshes.
Does anyone know what the problem is?