views:

393

answers:

4

How do I grab the controls inside of a UserControl tag?

So if this is on a Page:

<ME:NewControl ID="tblCustomList" runat="server">
// ... these controls will be used in my UserControl.aspx
</ME:NewControl>

How do I access those controls in my UserControl?

For instance, the Table class does this:

<asp:Table ID="tblNormal" runat="server">
  <asp:TableRow>
      <asp:TableCell>Thing 1</asp:TableCell>
      <asp:TableCell>Thing 2</asp:TableCell>
  </asp:TableRow>
</asp:Table>

I get an error saying my UserControl "does not have a public property named 'TableRow', when I do this:

<ME:NewControl ID="tblCustomList" runat="server">
  <asp:TableRow>
      <asp:TableCell>Thing 1</asp:TableCell>
      <asp:TableCell>Thing 2</asp:TableCell>
  </asp:TableRow>
</ME:NewControl>

I found this sample to help extend the Table class, but it's not exactly what I want to do.

I also found this description of how to use Templated Controls, which I'm not sure if I can use.

A: 

I am not sure if I understand the question 100%.

However if you a custom control called Row you can add a collection to the main table user control.

You can do this with a generic list. This should give you the ability to add them like a normal aspx control.

I don't have a code sample here, but I have done it many times.

David Basarab
A: 

I am not sure i understand your question.

You could access the controls server side by just using tblCustomList.Controls and then you could loop and add to your usercontrol. But again, i am not sure what you are asking.

Victor
Maybe I'm not being clear that the code above would actually go on the page. I'll also include the error message I'm getting in a second here.
Jon Smock
A: 

The sample that you referenced seems to be what you're trying to accomplish.
Have you added the following to the code behind?

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;

namespace Samples.AspNet.CS.Controls
{
    [AspNetHostingPermission(SecurityAction.Demand, 
        Level = AspNetHostingPermissionLevel.Minimal)]
    public sealed class CustomTableCreateControlCollection : Table
    {
        protected override ControlCollection CreateControlCollection()
        {
            // Return a new ControlCollection
            return new ControlCollection(this);
        }
    }
}
Gavin Miller
+1  A: 

Turns out I just needed something like this:

public TableRow DTHeader { get; set; }

protected override void OnInit(EventArgs e)
{
    tblCollection.Rows.Add(DTHeader);
    base.OnInit(e);
}

And then use this on my Page:

<ME:NewControl ID="tblCustomList" runat="server">
    <DTHeader>
        <asp:TableCell></asp:TableCell>
        //...
    </DTHeader>
</ME:NewControl>
Jon Smock