You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET C#中根据当前日期设置GridView过期行颜色问题求助

Hey there! Let's sort out how to highlight those expired rows in red—super common scenario, and there are a couple of solid ways to pull this off depending on how you're rendering your data. Let's break down the most typical approaches:


1. Handle it in the Backend (Using GridView's RowDataBound Event)

If you're working with ASP.NET Web Forms and using a GridView, the RowDataBound event is your best friend here. It fires every time a row gets bound to data, so you can check the date and style the row right then.

First, set up your GridView in the markup (make sure to hook up the event):

<asp:GridView ID="gvOrders" runat="server" OnRowDataBound="gvOrders_RowDataBound">
    <Columns>
        <asp:BoundField 
            DataField="DateOfRecd" 
            HeaderText="收货日期" 
            DataFormatString="{0:yyyy-MM-dd}" 
            HtmlEncode="false" />
        <!-- Add your other columns here -->
    </Columns>
</asp:GridView>

Then add this code to your code-behind:

protected void gvOrders_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // Only target actual data rows (skip headers/footers)
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Get the DateOfRecd value from your data source
        // Adjust this based on your actual data type (DataRowView, entity class, etc.)
        DateTime? dateOfRecd = DataBinder.Eval(e.Row.DataItem, "DateOfRecd") as DateTime?;
        
        // Make sure the date isn't null before comparing
        if (dateOfRecd.HasValue)
        {
            // Use DateTime.Today to compare just the date part (ignore time)
            if (dateOfRecd.Value < DateTime.Today)
            {
                // Set row background to red directly
                e.Row.BackColor = System.Drawing.Color.Red;
                
                // OR use a CSS class for more flexibility (recommended!)
                // e.Row.CssClass = "expired-row";
            }
        }
    }
}

A couple quick notes:

  • If you're binding to a strongly-typed entity (like an Order class), you can cast the DataItem directly instead of using DataBinder.Eval:
    var order = (Order)e.Row.DataItem;
    DateTime? dateOfRecd = order.DateOfRecd;
    
  • Using DateTime.Today instead of DateTime.Now avoids issues with time—so a delivery date of today won't get marked as expired just because it's earlier in the day.

2. Handle it with Frontend JavaScript

If you're using Razor Pages/MVC, or prefer to handle styling client-side, this approach works great too. Just render your table normally, then use JS to check dates after the page loads.

First, render your table with a class on the date cell so we can target it:

<table id="ordersTable" class="table">
    @foreach (var order in Model.Orders)
    {
        <tr>
            <td class="recd-date">@order.DateOfRecd.ToString("yyyy-MM-dd")</td>
            <!-- Other columns -->
        </tr>
    }
</table>

Then add this script (either in your view or a separate JS file):

document.addEventListener('DOMContentLoaded', function() {
    // Set current date to midnight to ignore time differences
    const currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);

    // Loop through all table rows
    document.querySelectorAll('#ordersTable tr').forEach(row => {
        const dateCell = row.querySelector('.recd-date');
        if (dateCell) {
            const recdDate = new Date(dateCell.textContent.trim());
            // Compare the dates (JS handles date objects directly)
            if (recdDate < currentDate) {
                row.style.backgroundColor = 'red';
                // OR use a CSS class for better control
                // row.classList.add('expired-row');
            }
        }
    });
});

Pro tip: Using a CSS class instead of inline styles lets you easily tweak the look later (like adding text color changes, borders, etc.). Just define the class in your stylesheet:

.expired-row {
    background-color: #ffcccc; /* Light red, easier to read than pure red */
    color: #dc3545;
}

Common Pitfalls to Watch For

  • Null Dates: Always check if DateOfRecd is nullable—you don't want a null reference exception!
  • Date Format Issues: Make sure your date string is in a format JS can parse (yyyy-MM-dd is safest).
  • Time Zone Differences: If your app handles multiple time zones, ensure you're comparing dates in the same time zone (consider converting to UTC if needed).

Hope this gets you sorted out! Let me know if you need to adjust this for your specific setup.

内容的提问来源于stack exchange,提问作者Forkan Akon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:20:44