简体   繁体   English

在代码隐藏中将 CSS 添加到 GridView

[英]Adding CSS to GridView in Code Behind

I am trying to style my GridView object but I can't seem to get it to use the CSS class.我正在尝试设置 GridView 对象的样式,但似乎无法让它使用 CSS 类。 I am creating the GridViews dynamically, so they are all created in code-behind.我正在动态创建 GridViews,因此它们都是在代码隐藏中创建的。 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:以及在 RowDataBound 事件中:

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

and yet I still cannot style my data.但我仍然无法设计我的数据。 Any advice is greatly appreciated任何意见是极大的赞赏

    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这应该可以工作,但您需要确保将 css 类放在正确的位置或链接..否则您将无法应用样式

Your Css class declaration should look something like the following in head tag or link:您的 CSS 类声明在 head 标记或链接中应如下所示:

.controlbackcolor { background: green; .controlbackcolor { 背景:绿色; font-weight: bold;字体粗细:粗体; color: White;白颜色; } }

The best way is to assign CssClass, as you are doing.最好的方法是分配 CssClass,就像你在做的那样。 And then control style using selectors like this:然后使用这样的选择器控制样式:

Codehind代码隐藏

MyGridView.CssClass = "aclass";

CSS 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. Gridview 在 HTML 中呈现为普通表格,因此您可以在 CSS 端执行此操作以减少加载后的代码。

Bootstrap class can also be added in code behind like Bootstrap 类也可以添加到后面的代码中,例如

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");
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM