Adding CSS to GridView in Code Behind

17,391

Solution 1

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[1].CssClass = "controlbackcolor";
            e.Row.Cells[3].CssClass = "controlbackcolor";
        }
    }

this should work but you need to make sure that the css classes are put in the right place or linked.. otherwise you wont get the style applied

Your Css class declaration should look something like the following in head tag or link:

.controlbackcolor { background: green; font-weight: bold; color: White; }

Solution 2

The best way is to assign CssClass, as you are doing. And then control style using selectors like this:

Codehind

MyGridView.CssClass = "aclass";

CSS

.aclass{Border: 1px solid lighgray;}
.aclass tr td {background:green; font-weight:bold; color: white}

Gridview is rendered as normal table in HTML, so you can do this on CSS side to reduce code behind load.

Solution 3

Bootstrap class can also be added in code behind like

protected void gvEmpContactsHistory_SelectedIndexChanged(object sender, EventArgs e)
    {
        string val = Convert.ToDateTime(gvEmpContactsHistory.SelectedDataKey.Value).ToString("dd-MM-yyyy hh:mm:ss", new System.Globalization.CultureInfo("en-US"));
        GetEmployeeDetail(val);

        foreach (GridViewRow row in gvEmpContactsHistory.Rows)
        {
            if (row.RowIndex == gvEmpContactsHistory.SelectedIndex)
            {
                row.ToolTip = string.Empty;
                row.Attributes.Add("class", "btn-success");
            }
            else
            {
                row.ToolTip = "Click to select this row.";
                row.Attributes.Add("class", "btn-outline-success");
            }
        }
    }
Share:
17,391
Jenny54321
Author by

Jenny54321

Updated on June 14, 2022

Comments

  • Jenny54321
    Jenny54321 almost 2 years

    I am trying to style my GridView object but I can't seem to get it to use the CSS class. I am creating the GridViews dynamically, so they are all created in code-behind. I have tried the following and nothing seems to work.

    for (...)
    {
     GridView gv = new GridView();
     gv.CssClass = "aclass";
     gv.Attributes.Add("class", "aclass");
    }
    

    and also in the RowDataBound event:

    foreach (row in gv)
    e.Row.Cells[i].CssClass = "aClass";
    

    and yet I still cannot style my data. Any advice is greatly appreciated