Roland
Roland

Reputation: 5226

How to replace an entire ASP control

I want to display a lot of data in a Table control, but put the code in a library method that returns a new Table object. When I assign that object directly to the control on the ASP page, the data does not show.

The library method looks like this:

public Table CreateTable(...)
{
   Table tbl = new Table();
   ...
   // adding lots of cells and setting lots of properties
   ...
   return tbl;
}

The ASP page has a Table control:

<asp:Content ID= ... >
    <asp:Table ID="Table_Data" runat="server">
    </asp:Table>
</asp:Content>

In Code-Behind the Table control is assigned the new Table object:

protected void Button_Click(object sender, EventArgs e)
{
    Table_Data = Lib.CreateTable(...);
}    

but when tested the Table control shows empty.

This principle has worked by this:

Table NewTable = Lib.CreateTable(...);
PlaceHolder1.Controls.Add(NewTable);

but it seems that having a PlaceHolder in my asp page should not be needed. Or is it?

Any help is appreciated!


Update:

The solution is, as the Accepted Answer, to keep the PlaceHolder, but not <asp:Content> but a new PlaceHolder control at the exact place where I want the table:

<asp:PlaceHolder ID="PlaceHolder_Table" runat="server">
</asp:PlaceHolder>

and in Code Behind:

PlaceHolder_Table.Controls.Add(Lib.CreateTable(...));

Simple, and works great.

Upvotes: 1

Views: 140

Answers (2)

lem2802
lem2802

Reputation: 1162

<asp:Content ID="contId" >
    <asp:Table ID="Table_Data" runat="server">
    </asp:Table>
</asp:Content>

protected void Button_Click(object sender, EventArgs e)
{
    contId.Controls.Clear();
    contId.Controls.Add(Lib.CreateTable(...));
} 

Upvotes: 2

sr28
sr28

Reputation: 5106

The asp.net table control isn't supposed to work like this. You're most likely looking for the GridView control, see here. This is used for getting data, binding it to the Gridview and displaying it

The asp.net table control info is here. It's more of a format thing rather than using for loads of data, that's why you can't databind to it.

Upvotes: -1

Related Questions