Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-使用变量值查找现有变量名_C#_Asp.net_Webforms - Fatal编程技术网

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

C#-使用变量值查找现有变量名,c#,asp.net,webforms,C#,Asp.net,Webforms,我在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.

我在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控件表示。不一定是这种情况,您也可以用
表示它,在这种情况下,您需要转换到的类型是不同的

还要注意tdParentControl-它应该是
td
s的直接父控件,因为FindControl不是递归的

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

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

这里的假设是“TD”由TabelEL控件表示。不一定是这种情况,您也可以用

表示它,在这种情况下,您需要转换到的类型是不同的

还要注意tdParentControl-它应该是
td
s的直接父控件,因为FindControl不是递归的

var tableCell = tdParentControl.FindControl("td" + g) as TableCell;
if (tableCell != null)
    tableCell.Style.Add("background-color", "#FFFF00");
最后,考虑使用CSS类而不是内联样式。< > >代码>字典动作=新{{ 1,()= >TD1..Dype。添加(“HRP”,“Delp”)},/*YADA*/} < /代码>然后<代码>动作[g]();
Dictionary actions=new{{1,()=>td1.Style.Add(“herp”,“derp”)},/*yadda*/}
then
actions[g]()非常感谢,它成功了;)它只与FindControl一起工作,我没有使用tdParentControl,我使用了,它的类型是System.Web.UI.HtmlControl.HtmlTableCell:)非常感谢,它工作了;)它只使用FindControl,我没有使用tdParentControl,我使用了,它的类型是System.Web.UI.HtmlControl.HtmlTableCell:)