2017-06-13 72 views
0

我有一个Web应用程序ASP.NET项目的页面的.cs这段代码:C# - 使用一个变量的值,以找到一个现有的变量名

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"); 

这可能吗?

+0

'动词= [{1,()=> – Will

回答

2

这里的假设是“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类而不是内联样式。

+0

非常感谢,它工作;)它只与FindControl一起工作,我没有使用tdParentControl,我用,它的类型是System.Web.UI.HtmlControls.HtmlTableCell :) –

相关问题