Search code examples
c#asp.netuser-interface

dynamically add a link button in gridview template field at run time together a label control


I have a gridview in my form. I am working with RowDataBound event to the grid. Now I have a template field inside columns of the gridview. A label has been taken inside template field. I want to add a link to this label on RowDataBound event at runtime, but .System.Web.UI.WebControls.LinkButton is showing instead of link button. How do I add a link button with label text in the grid view?


Solution

  • Just add a linkbutton inside your templatefield

    <asp:GridView runat="server" ID="gridView">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton runat="server" ID="lnkTest"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    

    Then in your rowdatabound event you can find it and do whatever you want

    void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Entity entity = e.Row.DataItem as Entity;
    
                LinkButton lnkTest = e.Row.FindControl("lnkTest") as LinkButton;
                lnkTest.CommandArgument = entity.ID.ToString();
                lnkTest.Text = entity.Name;
            }
        }
    

    You can then subscribe to gridview Command event and correct CommandArgument will be passed when clicking by linkbutton. Hope this helps.