C# - 使用变量值查找现有变量名称



我在 Web 应用程序 ASP.NET 项目的.cs页面中有以下代码:

protected void coloratd_Click(object sender, EventArgs e)
{
    Button B = sender as Button;
    int g = Convert.ToInt32(B.Text);
    if (g == 1) td1.Style.Add("background-color", "#FFFF00");
    else if (g == 2) td2.Style.Add("background-color", "#FFFF00");
    else if (g == 3) td3.Style.Add("background-color", "#FFFF00");
    else if (g == 4) td4.Style.Add("background-color", "#FFFF00");
    else if (g == 5) td5.Style.Add("background-color", "#FFFF00");
    else if (g == 6) td6.Style.Add("background-color", "#FFFF00");
    else if (g == 7) td7.Style.Add("background-color", "#FFFF00");
    else if (g == 8) td8.Style.Add("background-color", "#FFFF00");
    else if (g == 9) td9.Style.Add("background-color", "#FFFF00");
    else if (g == 10) td10.Style.Add("background-color", "#FFFF00");
}

用户单击表格的 td 元素(td1、td2...(中的按钮,然后 td 单元格变为黄色。上面的代码是正确的,但我想知道是否有办法使用 g 值直接与 td 项目交互,例如:

"td"+g.Style.Add("background-color", "#FFFF00");

可能吗?

这里的假设是"td"由 TableCell 控件表示。不一定是这种情况,您也可以用 <td runat="server"> 表示它,在这种情况下,您需要转换为的类型是不同的。

另请注意 tdParentControl - 它应该是 td 的直接父控件,因为 FindControl 不是递归的。

var tableCell = tdParentControl.FindControl("td" + g) as TableCell;
if (tableCell != null)
    tableCell.Style.Add("background-color", "#FFFF00");

最后,考虑使用 css 类而不是内联样式。

最新更新