2009-05-27 43 views
9

我想将一个CSS类附加到RowDataBound上的一行上。我对GridView使用交替的css类属性,所以我假设这是应用在RowDataBound上的。如果您在RowDataBound事件中以编程方式将CSS类指派给行的CssClass属性,则不应用交替的行样式css类,即使附加了CSS类,也应该使用在RowDataBound上添加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 

previousExpenseType就是我正在做的比较反对的字符串。如果费用类型发生变化,那么我希望将边框应用于<tr>元素的底部。

任何想法如何解决这个问题?看起来在RowDataBound之后有一个事件将交替的行样式css类应用到行中。

回答

2

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

+0

是的,这就是我希望不听,但它似乎是目前最可行的解决方案。 – Kezzer 2009-05-27 13:15:27

+0

我明白。绝对不是理想,但如果你所说的是对覆盖你正在做的事情的一个可能的隐藏事件是真实的,我不能想出很多方法来规避这种情况,而没有任何一个)去除任何项目风格和替代的规则行风格(不需要)或b)在事实之后走动并做需要做的事情。 – TheTXI 2009-05-27 13:26:02

-1

Gridview rowdatabound仅允许您在TR内操纵HTML,因此您可能没有选择使用gridView执行您想要的操作。相反,我会建议使用Repeater,它可以让你更好地控制你生成的HTML。这里是你可以与中继器

<table> 
    <thead> 
     <tr><td>Head1</td><td>Head2</td></tr> 
    </thead> 
    <asp:Repeater ID="rptTaskItems" runat="server"> 
     <ItemTemplate> 
      <tr><td>column 1 data</td> 
       <td>column 1 data</td> 
      </tr> 
      <asp:PlaceHolder ID="PHBar" runat="server" visible="false"> 
      <tr><td colspan="2"><hr/></td> 
      </tr> 
      </asp:PlaceHolder> 
     </ItemTemplate> 
    </asp:Repeater> 
</table> 

在的ItemDataBound做什么,你只能当你的条件为真这就是它使这个占位符[PHBar]可见。

希望这会有所帮助。

+0

我不知道,你的立场与此是。 CssClass属性确实工作,我的问题是在RowDataBound之后发生的隐藏事件不会附加交替的CSS类。我正在应用CSS类,因此我正在操纵HTML。 – Kezzer 2009-05-27 11:50:21

+0

似乎有点苛刻的凯兹;) – Chris 2017-07-29 01:27:41

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... 
     // 
    } 
} 
+0

您可能希望执行'row.RowState.HasFlag(DataControlRowState.Alternate)',因为'DataControlRowState'是'Flags enum'。自那时以来,.NET框架可能已经发生了变化,至少在VS2010/.net 4中添加了'HasFlag'。 – Andrew 2016-07-28 08:40:14