user489041
user489041

Reputation: 28294

Add ASP Controls to a Table Dynamically

Right now I have an ASP Table. I can add rows and cells to this table just fine. What I would like to do, is instead of the cell just displaying text, I would like to add a control. For example a Button.

Right now, my first thought on how to do this would be just to put the <ASP:Button ... as the .Ttext attribute of the table cell. But my gut tells me this wont work. Further more, I probably couldn't add a function to handle the button click.

Can someone help point me in the right direction on how to achieve this?

Upvotes: 4

Views: 10683

Answers (3)

theG
theG

Reputation: 585

The following assumes you have a blank ASP:Table on your page with some defined rows (just for show really).

protected void Page_Init(object sender, EventArgs e)
{
    foreach (TableRow row in this.Table1.Rows)
    {
        foreach (TableCell cell in row.Cells)
        {
            Button btn = new Button();
            btn.Text = "Some Button";
            btn.Click += new EventHandler(btn_Click);
            cell.Controls.Add(btn);
        }
    }
}

void btn_Click(object sender, EventArgs e)
{
    ((Button)sender).Text = "Just Clicked";
}

Upvotes: 2

Joel Coehoorn
Joel Coehoorn

Reputation: 415705

The question hangs on what the source is for your controls. Bar far, the most effective way to make this happen is through data binding, even if your data source is just the Enumerable.Range() function.

Failing that, you need to create an instance of your controls and add them to the Control's collection of the table cell they will belong in. You can just use the += syntax for adding event handlers. The trick here is that the code to create and add the button will need to run again on every postback, and it will need to run before the page_load phase of the asp.net life cycle.

Upvotes: 0

Paul
Paul

Reputation: 51

You need to add the control to the table cell. Just call the Controls.Add method on the cell and add your control. Below is a brief sketch that should point you in the right direction.

        Button b = new Button();
        c.Controls.Add(b);

Upvotes: 5

Related Questions