首页 > 解决方案 > 在 ASP.NET C# 中使用 SQL 查询对 Datatable 行着色

问题描述

我需要为我的 asp.net c# 表的行着色。为了显示表格,我使用一个 ASP:Repeater 和 html:

<div class="panel-body">
<div class="table-responsive">
    <table class="table table-striped table-bordered table-hover" id="dataTables-MaquinasCaidas" >
        <thead>
            <tr>
                <th>Hora Reportada</th>
                <th>Máquina</th>
            </tr>
        </thead>
        <tbody>
            <asp:Repeater ID="repeaterMaquinaCaida" runat="server">
                <ItemTemplate>

                    <tr>
                        <td>
                            <asp:Label ID="lblHoraReportada" runat="server" Text='<%# Eval("HoraReportada") %>' />
                        </td>
                        <td>
                            <asp:Label ID="lblNoMaquina" runat="server" Text='<%# Eval("NoMaquina") %>' />
                        </td>
                    </tr>

                </ItemTemplate>
            </asp:Repeater>
        </tbody>
    </table>
</div>

在 .cs 页面中,填写表格:

public void fillTable()
    {
        string query = "SELECT * FROM MaquinaCaida order by HoraReportada asc";
        DataTable tableResponse = SqlComm.SqlDataTable(query);
        TableRow row = new TableRow();
        TableCell cell = new TableCell();
        if (!IsPostBack)
        {
            repeaterMaquinaCaida.DataSource = tableResponse;
            repeaterMaquinaCaida.DataBind();
        }

我只需要根据条件为一些行着色,例如:

SELECT * FROM Table WHERE Column = "something";

然后将行的颜色更改为红色,例如。

有没有办法执行此操作?

标签: c#htmlasp.net

解决方案


您可以点击 ItemDataBound 事件,检查特定条件的行数据源,然后更改行类。

<asp:Repeater ID="repeaterMaquinaCaida" runat="server" OnItemDataBound="ItemDataBound"

void ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
  // Execute the following logic for Items and Alternating Items.
  if (e.Item.ItemType == ListItemType.Item ||
      e.Item.ItemType == ListItemType.AlternatingItem)
  {
    if (((Evaluation)e.Item.DataItem).Rating == "Good") //check your logic here
    {
      ((Label)e.Item.FindControl("RatingLabel")).Text= "<b>***Good***</b>"; //change row here
    }
  }
} 

https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeater.itemdatabound?redirectedfrom=MSDN&view=netframework-4.8


推荐阅读