Search code examples
c#asp.netgridviewuser-controlsrowdatabound

Access a UserControl in a Gridview from the RowDatBound method


I have a gridview and within the item template i have a usercontrol which is losing it's value on postback. I want to be able to access the control from my RowDataBound method in the c# code behind and reassign the CandidateID value

GridView Control

<asp:TemplateField>
    <ItemTemplate>

        <Controls:LikeButton ID="CandidateLikeButton" runat="server" LikeType="Candidate"
           LikedObjectID='<%# Bind("CandidateID") %>' />

    </ItemTemplate>
</asp:TemplateField>

How can i do this?


Solution

  • You can access it with FindControl like any other Control and cast it back to it's type.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LikeButton LB = e.Row.FindControl("CandidateLikeButton") as LikeButton;
    
            LB.CandidateID = 1234;
        }
    }