Dynamically adding a command button to a GridView
<p>I'm having an issue with trying to add a button to my grid. My GridView is first loaded with data in the PageLoad event.</p>

<p>I'm then taking the data in the first cell of each row, and creating a button that will link to a URL. To get the URL, I have to run a query with the data in the first cell as a parameter. I was doing this in the RowDataBound event at first, but hitting that query for every row was making it really slow.</p>

<p>So I decided to add a button that would retrieve the URL only when you clicked the button.</p>

<p>Here's my GridView:</p>

<pre><code>&lt;asp:GridView ID="gvResults" runat="server"
    OnRowDataBound="gvResults_RowDataBound"
    OnRowCommand="gvResults_RowCommand"&gt;               
&lt;/asp:GridView&gt;    
</code></pre>

<p>And my code:</p>

<pre><code>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;
    }
}
</code></pre>

<p>The grid generates fine, the button gets added to the grid for each row. But when I click on it, the RowCommand event doesn't fire, and the page just refreshes.</p>

<p>Does anyone know what the issue is?</p>
