Search code examples
c#htmlasp.netgridviewitemtemplate

Dynamically change the class of a div nested in a gridview item template from code behind c#


I need to change the class of a div nested inside a gridview item template, i have given the runat="server" tag and an id for the div. How can we change the class of that particular div upon gridview databind based on each row conditions.


Solution

  • ASPX

    <asp:GridView ID="gv" runat="server" OnRowDataBound="gv_OnRowDataBound">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <div id="yourDiv" runat="server"></div>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    

    Code-behind

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e) {
        if (e.Row.RowType == DataControlRowType.DataRow) {
            HtmlGenericControl div = (HtmlGenericControl)e.Row.FindControl("yourDiv");
            div.Attributes.Add("class", "ClassYouWantToAdd");
        }
    }