0

I have this code in a .cs page of a Web Application ASP.NET project:

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

The user clicks a button which is in a td element of a table (td1, td2...) and then the td cell becomes yellow. The code above is correct but I'd like to know if there's a way to use the g value to interact directly with a td item, for example this:

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

Is it possible?

1
  • Dictionary<int, Action> actions= new { { 1, () => td1.Style.Add("herp", "derp")}, /*yadda*/ } then actions[g](); Commented Jun 13, 2017 at 17:18

1 Answer 1

2

The assumption here is that "td" is represented by TableCell control. Not necessarily the case, you could also have it represented by <td runat="server">, in which case the type you need to cast to is different.

Also note the tdParentControl - that should be the immediate parent control of the tds, because FindControl is not recursive.

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

Finally, consider using css classes instead of inline styles.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, It worked ;) It worked with only FindControl, I didn't use tdParentControl, I used <td runat="server"> and its type is System.Web.UI.HtmlControls.HtmlTableCell :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.