views:

379

answers:

1

On one of our pages, we've got a table that has rows generated at runtime. I want to move the content of those rows out into their own control and set properties on it at runtime, in order to separate the presentation from the code-behind. But it's not working the way I'm expecting.

If I have my row-like control inherit from UserControl, then I can do this to create the control at runtime:

MyControl row = (MyControl)LoadControl("~/controls/MyControl.ascx");

Then, I wanted to add that to my table:

MyTable.Rows.Add(row);

But row does not inherit from System.Web.UI.HtmlControls.HtmlTableRow or System.Web.UI.WebControls.TableRow, so you can't do that. However, if I make my control inherit from one of those two, then the LoadControl call above complains that the control doesn't inherit from UserControl.

What's the happy solution here? If additional information is needed, please ask.

+3  A: 

I think what you're looking to do is this:

    MyControl row = (MyControl)LoadControl("~/controls/MyControl.ascx");
    TableCell newCell = new TableCell();
    newCell.Controls.Add(row);
    TableRow newRow = new TableRow();
    newRow.Cells.Add(newCell);
    MyTable.Rows.Add(newRow);

The problem as you stated is that your control cannot inherit from multiple base classes and you cannot add your control directly to the Rows collection. You need to first wrap it. There may be cleaner solutions, but this one does work.

Alexander Kahoun