Help on User controls ... ascx

I am aware of when and why to use user control .. advantages/disadvantages .. difference between user controls and web custom controls etc etc ..

I have created a user control which contains a DHTML menu and some textboxes. I have a basepage which is inherited by all my other pages within the project. As the menu has to be placed on the top of almost all of these pages, what I have done is

1. dynamically add the control in the load event of the basepage. When I added the usercontrol using loadcontrol, it gave the error that the controls have to be within the form tags with runat=server (as there are other controls like textbox within the usercontrol) .. So I used a findcontrol of the formId (page.FindControl("Form1")) and added the usercontrol to the first index of controls using "AddAt" .. But then this logic requires that all my pages which inherits the basepage name the form as "Form1" which is what is been used by the BasePage ... I do not want to use a placeholder as then this would mean that I will have to add the placeholder in all the Pages which inherits the BasePage .. Help needed here on any other approach ...

2. Expose a property (Boolean .. default is true) within the usercontrol .. this is used by the basepage to decide whether the usercontrol has to be shown in the current page or not (CurrentPage inherits basepage) .. this is set in the load of the current page. Now the usercontrol is loaded in load event of the basepage .. So if i set this property within the load event of the CurrentPage, then it is not set within the usercontrol as the load of the basepage gets run first .. So should the usercontrol be added in the init of the basepage? If yes, is this the correct approach or just a workaround??

3. Now how will I access the controls within the usercontrol (the names are generated as _ct10_txtTextBoxName) .. would these names ever change in subsequent addition of more controls to the usercontrol or compilations .. what is the correct method/logic to acheive all this .. Help needed here too .. links to any tutorials examples which explain these concepts is appreciated .. I did search for examples and most of the articles talks about adding usercontrol to the page during design time and most of the usercontrols do not have any other controls within it (seen examples of usercontrol menus using DHTML) ..

Hope this discourse hasn't been very lengthy and hope you had the patience to reach the end and help me out here ..

Thanks a lot in advance

LVL 26
Who is Participating?
reference: (a bit complex implementing some functionality found in ASP.NET 2.0) (my recommendation, but not all of the code though...)

foot note
1. You can also store your templates in Xml and load them in the Cache object with a file dependency on the xml files.
2. I have also used XSLTs with the Xml to change the look and feel of the pages without re-compiling code.
BasePage example
Imports System.Text
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Collections

Public Class BasePage
      Inherits System.Web.UI.Page
      Private Shared builder As StringBuilder
      Private Shared ReadOnly Property Html() As String
                  If builder Is Nothing Then
                        builder = New StringBuilder
                        builder.AppendFormat("<title><asp:Literal Id='{0}' runat='server' /></title>","TitleLiteral")
                        builder.Append("<link rel='stylesheet' type='text/css' href='{0}' />",ResolveUrl("~/stylesheet/global.css")
                        builder.Append("<form id='BasePageForm' runat='server' />")
                  End If
                  Return builder.ToString
            End Get
      End Property
      Public Sub New()
      End Sub
      Protected Overridable Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
            Dim controls As Control() = GetControls()
      End Sub
      Protected ReadOnly Property FormElement() As HtmlForm
                  Return DirectCast(FindControl("BasePageForm"),HtmlForm)                  
            End Get
      End Property
      Private ReadOnly Property TitleLiteral() As Literal
                  Return DirectCast(FindControl("TitleLiteral"),Literal)
            End Get
      End Property      
      Protected Property PageTitle() As String
                  Return TitleLiteral.Text
            End Get
            Set (ByVal value As String)
                  TitleLiteral.Text = value
            End Set
      End Property
      Private Function GetControls() As Control()
            Dim list As New ArrayList
            For Each ctl in Page.Controls
            Return DirectCast(list.ToArray(GetType(Control)),Control())
      End Function
      Private Sub MoveControls(ByVal controls As Control())
            For Each ctl As Control In controls
      End Sub
End Class
RejojohnyAuthor Commented:
thx b1xml2 for the prompt reply.
Based on the approach you have suggested, all the controls within the page is removed and added after the usercontrol is added .. I have placed all the controls within tables and not using the style to position the controls .. so with ur approach, the posistioning of all my controls would be lost .. right? and would this not involve more processing everytime the page is accessed ?? any other suggestion?
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

<asp:TextBox Id="txtUserId" runat="server" />

Public Class MyPage
      Inherits BasePage
      Protected WithEvents txtUserId As TextBox
#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Protected Overrides Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
    End Sub

#End Region
End Class
RejojohnyAuthor Commented:
can you suggest any good reference materials that I can have a look at to get a better understanding on all this .... any links to an example on the web ..
Rejo, in short they are removed and added to a targetted control.

You can modify the HTML and move the controls to a different control instead of the HtmlForm. This allows for the implementation of Master Pages.

the processing hit appears minimal. I have used something similar to this in a commercial environment and there was no noticeable impact.

As for the styling, you can modify the HTML code to include even the <%@Register ... %> to register UserControl and add the standard UserControl syntax in the HTML text.

The positioning of the elements can always be managed in some way or form. You could use the following:

<asp:PlaceHolder Id="phControls" Runat="server" />

and move the controls to the PlaceHolder instead of the form.
RejojohnyAuthor Commented:
>>You can also store your templates in Xml and load them in the Cache object with a file dependency on the xml files.
hmm .. good idea .. let me think on those lines too ..

thx, I will have a look at the links provided

Will keep this open for a day .. maybe later, you would like to add somethng more or I might get lucky and some other experts might give some more valuable inputs ..
I think any styling issues can be resolved in some way. Havent seen an issue where it couldnt'. Also with this basepage methodology, you can also store viewstate server-side instead of client-side <GRIN>
good to get as much comments and opinions from everyone else.
RejojohnyAuthor Commented:
>>with this basepage methodology, you can also store viewstate server-side instead of client-side
what do u mean? do u mean use some cache/session/xml/database or some other storage mechanism to store the viewstate of each page for each session ? wouldn't I have to code for everything then?
Once you set it up in the base page, the implementation is taken off your hands, it does it automatically using the LosFormatter class. But storing the ViewState server-side is another issue altogether. All I am saying is that it can also be done at the base page thereby having a customised look and feel.
RejojohnyAuthor Commented:
Thx a lot b1xml2 for ur time ..
not a problem, rejo =)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.