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
Orderclass), you can cast theDataItemdirectly instead of usingDataBinder.Eval:var order = (Order)e.Row.DataItem; DateTime? dateOfRecd = order.DateOfRecd; - Using
DateTime.Todayinstead ofDateTime.Nowavoids 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
DateOfRecdis 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

