Wednesday, August 31, 2005

Accessing user controls from code behind

You could access user controls from code behind to add dynamic controls

Add a place holder in user control, and make it public in code-behind

In application pages, code-behind declare an object of type user control

' user control used to add links
Dim pageMyControl As MyUserControl 
Dim lnkNewLink As WebControls.LinkButton
Dim newLinkButtonIndex as Int32
' get the user control
pageMyControl = DirectCast(FindControl("ucMyControl"), MyUserControl) 
If Not pageMyControl Is Nothing Then
  lnkNewLink = New WebControls.LinkButton
  lnkNewLink.Text = " [NewLink] "
  lnkNewLink.ID = "lnkNewLink"
  lnkNewLink.CausesValidation = False
  ' Add event handler to the link button, 
  ' this function has to be written in page code-behind
  AddHandler lnkNewLink.Click, AddressOf ControlNewLink 
  ' Add the link button to user control
  pageMyControl.phLinks.Controls.Add(lnkNewLink) 
  ' if incase you want to show/hide the link button based on certain condition
  ' or change properties of the link button based on codition,
  ' the index is required
  newLinkButtonIndex = pageMyControl.phLinks.Controls.IndexOf(lnkNewLink)
  ' heres an example to set visible property to false
  pageMyControl.phLinks.Controls(newLinkButtonIndex).Visible = False
End If

No comments: