【问题标题】:change color of a specific cell in a htmlTable更改 htmlTable 中特定单元格的颜色
【发布时间】:2013-01-21 11:17:49
【问题描述】:

我有一个 htmltable。表格的每个单元格都由一个 ID 标识,例如 0001 等。该表没有固定维度,而是动态的,因此可以有 20 个或更多单元格,具体取决于 db 中存储了多少值。我想更改特定单元格的文本框的背景颜色。但不知道如何访问单元格。

我知道这种语法:

// the whole background becomes green 
myTable.BgColor = "#008000"; 
// I see no changes
myTable.Rows[x].Column[y].BgColor = "#008000";


// I need a syntax like this
myTable.Cell(Id_cell).BgColor =  "#008000";

【问题讨论】:

    标签: c# asp.net html-table


    【解决方案1】:

    您可以像这样设置单个单元格的背景颜色:

    myTable.Rows[0].Cells[1].BgColor = "#553322";
    

    其中 0 是您想要的行号,在这种情况下是第一行,1 是您想要的单元格编号,在这种情况下,第二个单元格作为索引基于 0。这必须在表格呈现之前完成,例如在页面加载时。

    您可以将此概括为一种为 id 设置单元格颜色的方法,如下所示:

    private void SetColorByCellId(HtmlTable table, string id, string color)
    {
        for (int i = 0; i < table.Rows.Count; i++)
        {
            for (int j = 0; j < table.Rows[i].Cells.Count; j++)
            {
                if (table.Rows[i].Cells[j].ID == id)
                {
                    table.Rows[i].Cells[j].BgColor = color;
                }
            }
        }
    }
    

    那么你可以这样称呼它:

    SetColorByCellId(myTable, "0001", "#553322");
    

    【讨论】:

    • 这似乎是个好主意,但是 table.Rows[i].Cells[j].ID 总是返回 null,为什么?
    【解决方案2】:

    试试这个:

    .aspx:

    <asp:Table ID="table" runat="server" />
    

    C#代码:

    TableRow row = new TableRow();
    TableCell cell = new TableCell();
    cell.Text = "Testing";
    cell.BackColor = System.Drawing.Color.Red;
    row.Cells.Add(cell);
    table.Rows.Add(row);
    
    table.Rows[0].Cells[0].BackColor = System.Drawing.Color.Pink;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      相关资源
      最近更新 更多