Search code examples
cssasp.nethtml-tablebackground-colordynamic-controls

Background color not restored for dynamically generated controls (ASP.NET)


I am generating a <TABLE> dynamically in ASP.net. Based on certain events, I need to highlight (via background color) the specific cell <TD> in question and de-highlight any previously selected cell.

Sadly, after each event, the previously selected cells are still highlighted. I've written a small piece of code that replicates my problem with 2 buttons that simulate instances of two events.

Creation of Table ...

    protected void Page_Init(object sender, EventArgs e)
    {
        Table tbl = new Table();
        this.Controls.Add(tbl);

        TableRow row = new TableRow();
        tbl.Controls.Add(row);

        TableCell cell1 = new TableCell();
        cell1.Style.Add("background-color", "green");
        cell1.ID = "cell1";
        cell1.Text = "CELL 1";

        TableCell cell2 = new TableCell();
        cell2.Style.Add("background-color", "green");
        cell2.ID = "cell2";
        cell2.Text = "CELL 2";

        row.Controls.Add(cell1);
        row.Controls.Add(cell2);
    }

I highlight the first cell during this event

    protected void Button1_Click(object sender, EventArgs e)
    {
        TableCell ctr1 = (TableCell)this.FindControl("cell1");
        ctr1.Style.Add("background-color", "yellow");
    }

I highlight the second cell during this event. The first cell should no longer be highlighted as I have just recreated this table on postback !

    protected void Button2_Click(object sender, EventArgs e)
    {
        TableCell ctr2 = (TableCell)this.FindControl("cell2");
        ctr2.Style.Add("background-color", "yellow");
    }

Any help or pointers would be greatly appreciated ! An alternate approach to achieve the desired effect would be welcome too !


Solution

  • ViewState had come back to haunt me!

    When creating the dynamic controls setting EnableViewState = false solves the problems.

    Here, ASP.net was restoring the background color from ViewState and in most cases this is the behavior you want and expect for your dynamically generated controls !