在ASP.NET中满足特定条件后为所有其余行着色

时间:2020-05-05 20:12:02

标签: asp.net gridview webforms

在满足特定条件后如何在GridView的单元格中为所有剩余的行着色

带有模板列的网格

<asp:TemplateField HeaderText="Status" HeaderStyle-CssClass="grdHeader" ItemStyle-Width="22%">
                                         <ItemTemplate>
                                             <asp:Label ID="lblStatus" runat="server" ><%#DataBinder.Eval(Container.DataItem, "Status_Id")%></asp:Label>
                                         </ItemTemplate> 
                                    </asp:TemplateField>

例如,如果一个网格有10行,那么如果第四行中的Status_Id = 1,则我需要为其余所有6行着色。

使用RowDataBound事件如何实现

void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {

    }

  }

2 个答案:

答案 0 :(得分:0)

在RowDataBound中检查当前行的状态ID。如果它与您要查找的内容匹配,请在隐藏字段或全局变量等中设置一个值。同样在RowDataBound中,检查是否已设置该值。如果有的话,那么您就知道您已经越过找到状态ID的行,因此现在更改该行的行颜色。

答案 1 :(得分:0)

List<foo> lst = GetList();

StringBuilder sb = new StringBuilder();

sb.Append(@"
<div class='grdHeader'>
<table>
<tr>
<th>Status ID</th>
<th>Name</th>
<th>Amount</th>
</tr>
");

bool colorTheRest = false;

foreach (var foo in lst)
{
    if (colorTheRest)
    {
        sb.Append("<tr class='trColor'>");
    }
    else
    {
        sb.Append("<tr class='trNoColor'>");
    }

    if (foo.status == 1)
    {
        colorTheRest = true;
    }

    sb.Append($@"
<td>{foo.status}</td>
<td>{foo.name}</td>
<td>{foo.amount}</td>
</tr>
");
}

sb.Append("</table></div>");

在ASP.NET页上添加一个占位符:

<asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>

继续后面的代码:

ph1.Controls.Add(new LiteralControl(sb.ToString()));

然后,您可以在CSS样式块中为其着色:

<style type="text/css">
    .grdHeader th {
        /*your-style here*/
    }
    .trColor {
        background: gray;
    }
    .trNoColor {
        background: white;
    }
</style>
相关问题