在RowDataBound上添加CSS类

Kez*_*zer 9 asp.net

我正在尝试将一个CSS类附加到RowDataBound上的一行.我正在使用针对GridView的交替css类属性,所以我假设这适用于RowDataBound.如果以编程方式将CSS类分配给RowDataBound事件中行的CssClass属性,则即使附加CSS类,不会应用交替行样式css .

这是我得到的:

Protected Sub gvGeneral_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvGeneral.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
      If previousExpenseType <> e.Row.Cells(2).Text And previousExpenseType.Length > 0 Then
        e.Row.CssClass += "bottom-border"
      End If

      previousExpenseType = e.Row.Cells(2).Text
    End If
  End Sub
Run Code Online (Sandbox Code Playgroud)

previousExpenseType只是一个我正在做比较的字符串.如果费用类型更改,那么我希望将边框应用于<tr>元素的底部.

任何想法如何解决这个问题?在RowDataBound之后,似乎有一个事件将交替的行样式css类应用于该行.

bba*_*bba 13

在你的RowDataBound事件处理程序中尝试这个...

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridView grid = GridView1;
    GridViewRow row = e.Row;
    if (row.RowType == DataControlRowType.DataRow)
    {
        bool isAlternating = row.RowState == DataControlRowState.Alternate;

        List<string> classes = new List<string>();

        /*  Setting the CssClass of a row overwrites any CssClass declared in the 
         *  markup, so lets save the value that is in the markup and add to it.
         */
        if (isAlternating) { classes.Add(grid.AlternatingRowStyle.CssClass); }
        else { classes.Add(grid.RowStyle.CssClass); }

        //
        //logic for adding other css classes to the row...
        //

        //set the CssClass property of the row to the combined css classes value
        row.CssClass = string.Join(" ", classes.ToArray());

        //
        //more row processing...
        //
    }
}
Run Code Online (Sandbox Code Playgroud)


The*_*TXI 2

您可能想要尝试的另一种解决方法是在所有行都进行数据绑定后,通过使用后面的 gridview 事件之一并自己循环遍历行来执行检查和 CSS 类操作。我知道这会增加一些额外的处理时间,但根据您显示的数据集的大小,这可能是值得的。