2017-06-13 75 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 :) –

相關問題