如何为<td>及表格行添加背景色?(gridline.ascx.cs开发场景)
Hey there! Let’s walk through this step by step—no stress even if you’re not super familiar with gridline.ascx.cs. Since you already have code to show the imgBox control when wli.isBoxRequired is true, we’ll tie the background color change to that same condition.
Option 1: If your table is a data-bound control (like GridView/Repeater)
Most likely, your gridline.ascx uses a data-bound control to render rows. Here’s what to do:
Hook up the data binding event
First, open your gridline.ascx file, find your grid control (e.g.,<asp:GridView>), and add theOnRowDataBoundattribute (for GridView) orOnItemDataBound(for Repeater):<asp:GridView ID="dvLineItems" runat="server" OnRowDataBound="dvLineItems_RowDataBound"> <!-- Your existing columns here --> </asp:GridView>Add the event handler in gridline.ascx.cs
Now in the code-behind, create the event method to check your condition and set the row color:protected void dvLineItems_RowDataBound(object sender, GridViewRowEventArgs e) { // Only target actual data rows (skip headers/footers) if (e.Row.RowType == DataControlRowType.DataRow) { // Get your data item (replace `YourDataModel` with the actual type of wli) var wli = (YourDataModel)e.Row.DataItem; if (wli.isBoxRequired) { // Option A: Set direct background color e.Row.BackColor = System.Drawing.Color.LightYellow; // Option B: Use a CSS class (better for maintainability) // e.Row.CssClass += " required-row"; // Then add this to your ascx's style section: // <style>.required-row { background-color: #fff3cd; }</style> // Also make your imgBox visible here (if you want to consolidate code) var imgBox = (Image)e.Row.FindControl("imgBox"); imgBox.Visible = true; } } }
Option 2: If you’re manually rendering rows (not data-bound)
If your rows are created manually, you can adjust your existing code to find the parent row of imgBox and set its color:
if (wli.isBoxRequired) { var imgBox = (Image)dvLineItems.FindControl("imgBox"); imgBox.Visible = true; // Traverse up the control tree to find the parent TableRow // Adjust the number of .Parent calls based on your HTML structure (e.g., img → td → tr) TableRow targetRow = (TableRow)imgBox.Parent.Parent; // Set background color or CSS class targetRow.BackColor = System.Drawing.Color.LightYellow; // OR targetRow.CssClass += " required-row"; }
Quick Tips
- Double-check the control hierarchy: If
imgBox.Parent.Parentdoesn’t find the row, use your browser’s dev tools to inspect the HTML structure and adjust the number of.Parentcalls. - Using CSS classes is preferred over hardcoding colors—it makes it easier to update styles later without touching code.
内容的提问来源于stack exchange,提问作者gin toki

