与CSS冲突背后的C#代码

时间:2018-01-05 19:33:50

标签: c# html css asp.net webforms

我有一个asp:gridview,它有CSS和一个OnRowDataBound事件。如果我删除我的OnRowDataBound事件,CSS就像我想要的那样运行,但是如果我离开CSS和OnRowDataBound事件那么CSS就永远不会触发。

有人可以帮我解决这两种方法同时触发和运行的问题吗?

    ASP/HTML
<asp:GridView ID="gvEmps" runat="server" CssClass="Grid" OnRowDataBound="gvEmps_OnRowDataBound" >
    <Columns>
        <asp:BoundField DataField="EmpName" HeaderText="Name"> <ItemStyle CssClass="cellOneCellPadding" Width="50%" /></asp:BoundField>
        <asp:BoundField DataField="EmpAddress" HeaderText="Address"> <ItemStyle HorizontalAlign="Center"/></asp:BoundField>
        <asp:BoundField DataField="EmpCity" HeaderText="City"> <ItemStyle HorizontalAlign="Center"/></asp:BoundField>
        <asp:BoundField DataField="EmpState" HeaderText="State"> <ItemStyle HorizontalAlign="Center"/></asp:BoundField>
        <asp:BoundField DataField="EmpZip" HeaderText="Zip"> <ItemStyle HorizontalAlign="Center"/></asp:BoundField>
        <asp:BoundField DataField="EmpPhone" HeaderText="Phone"> <ItemStyle HorizontalAlign="Center"/></asp:BoundField>
    </Columns>
</asp:GridView>


C# Method gvEmps_OnRowDataBound....
if (e.Row.RowType == DataControlRowType.DataRow)
{
    foreach (TableCell row in e.Row.Cells)
    {
        if (design1.Any(x => x == e.Row.Cells[0].Text.ToUpper())) { row.CssClass = "des1"; }
        else if (design2.Any(x => x == e.Row.Cells[0].Text)) { row.CssClass = "des2"; }
        else if (design3.Any(x => x == e.Row.Cells[0].Text)) { row.CssClass = "des3"; }
        else { row.CssClass = "defaultview"; };
    }
} 

CSS
.cellOneCellPadding {
    padding-left: 9pt !important;
}

1 个答案:

答案 0 :(得分:2)

您在OnRowDataBound函数中重新分配CssClass属性并覆盖模板中最初提供的CssClass。改变你的foreach看起来像这样:

foreach (TableCell row in e.Row.Cells)
{
    if (design1.Any(x => x == e.Row.Cells[0].Text.ToUpper())) { row.CssClass += " des1"; }
    else if (design2.Any(x => x == e.Row.Cells[0].Text)) { row.CssClass += " des2"; }
    else if (design3.Any(x => x == e.Row.Cells[0].Text)) { row.CssClass += " des3"; }
    else { row.CssClass += " defaultview"; };
}