Find controls on sharepoint master page - asp.net

I'm trying to loop through all the controls on a sharepoint page, for the purposes of testing i just want to output the control ID
this is the code i'm using
Public Shared Sub SubstituteValues3(ByVal CurrentPage As Page, ByRef s As StringBuilder)
'Page()
'- MasterPage
'- HtmlForm
'- ContentPlaceHolder
'- The TextBoxes, etc.
For Each ctlMaster As Control In CurrentPage.Controls
If TypeOf ctlMaster Is MasterPage Then
HttpContext.Current.Response.Output.Write("Master Page <br/>")
For Each ctlForm As Control In ctlMaster.Controls
If TypeOf ctlForm Is HtmlForm Then
HttpContext.Current.Response.Output.Write("HTML Form <br/>")
For Each ctlContent As Control In ctlForm.Controls
If TypeOf ctlContent Is ContentPlaceHolder Then
HttpContext.Current.Response.Output.Write("Content Placeholder <br/>")
For Each ctlChild As Control In ctlContent.Controls
HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />")
Next
End If
Next
End If
Next
End If
Next
HttpContext.Current.Response.Output.Write("--------------")
HttpContext.Current.Response.End()
however it's not getting past the 'MasterPage' output.
I would expect to see the names of all the controls i have inside my content placeholder but i find it all a bit confusing.

Start with Page.Master.Controls
From there what you have should basically work
For Each ctlForm As Control In Page.Master.Controls
If TypeOf ctlForm Is HtmlForm Then
HttpContext.Current.Response.Output.Write("HTML Form <br/>")
For Each ctlContent As Control In ctlForm.Controls
If TypeOf ctlContent Is ContentPlaceHolder Then
HttpContext.Current.Response.Output.Write("Content Placeholder <br/>")
For Each ctlChild As Control In ctlContent.Controls
HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />")
Next
End If
Next
End If
Next

A MasterPage isn't a control of the current page, it's a property of it, in Page.MasterPage

i found this piece of code which seems list the controls I need, i think it's more of a hack though.
For i = 0 To CurrentPage.Request.Form.AllKeys.Length - 1
If CurrentPage.Request.Form.GetKey(i).Contains("ctl00$PlaceHolderMain$") Then
Dim key As String = CurrentPage.Request.Form.GetKey(i).Substring(22)
Dim keyText As String = String.Format("[{0}]", key)
HttpContext.Current.Response.Output.Write(keyText & "<br/>")
'Text.Replace(keyText, CurrentPage.Request.Form("ctl00$PlaceHolderMain$" & key))
End If
Next

you can do this simply with recursion, not efficent, but it is simple... try this method:
public void getControls(Control input)
{
foreach (Control c in input.Controls)
{
Response.Write(c.GetType().ToString() + " - " + c.ID + "<br />");
getControls(c);
}
}
And call it like this:
getControls(Page);
That will cycle trough all controls on your page and output the type - ID of them and print it out to the top of the page... you could also use the code to construct a list or whatever you want to do.

Related

Find checkbox that tharts with id

I'm trying to loop trough a bunch of checkboxes that start with a specific id.
This bit of code seems normal, but it doesn't find anything :
Dim childc As Control
Dim c as Control
For Each c In Me.Page.Controls
For Each childc In c.Controls
If TypeOf childc Is CheckBox Then
If CType(childc, CheckBox).Checked Then
If childc.ID.StartsWith("ctl00_indexBody_ID_ACTIVITE_") Then
i = i + 1
Alerte(CType(childc, CheckBox).Text)
strSQL = "INSERT INTO A_ACTIVITES VALUES("
strSQL += Me.ID_PRESTATAIRE.Text + "," + childc.ID + ","
strSQL += ")"
oWebConnection.Execute(strSQL)
End If
End If
End If
Next
Next
it breacks in the second line saying that
it's impossible to cast an objet of type 'ASP.masterpage_master' to 'System.Web.UI.WebControls.CheckBox
Thank's for your help
Declare c and childc as Control, not CheckBox.
The declaration of c is not visible but I think you made the same mistake.
I found a solution
Protected Sub GererActivite(ByVal oControls As ControlCollection)
Dim oControl As Control
For Each oControl In oControls
If oControl.HasControls Then
GererActivite(oControl.Controls) ' récursivité
ElseIf TypeOf oControl Is CheckBox Then
If CType(oControl, CheckBox).Checked Then
If CType(oControl, CheckBox).Text.StartsWith("ctl00_indexBody_ID_ACTIVITE_") Then
End If
End If
End If
Next
End Sub
This function runs trough a control Collection, and if a control of this collection has controls, i run trough these controls with the same function untill it finds a control that hasn't controls and if it is a checkbox, i can check on it as i wish.
It worked like a charm.
In fact it's my bosses idea i'm just bragging around, lol.
Hope it will help others.

Datagrid from Contentplace holder aspx page, Form is on Master page

This is asp.net application in VB. I have a master page and it has several contenet place holders have child pages. I have datagrid on those child or sub pages. I am trying to export these ASP:datagrids to excel. I know we have good examples of doing this. I am using following method:
Dim excelFileName As String = "Filename" + "_" + Date.Today + ".xlsx"
Response.Clear()
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=" + excelFileName)
Dim stringWriter As New System.IO.StringWriter()
Dim textWriter As New HtmlTextWriter(stringWriter)
dgrid.RenderControl(textWriter)
Response.Write(stringWriter.ToString())
Response.End()
My problem is I am not able to do it because it says that for using this code the grid and button should be under tag with property runat=Server. My trials were.
Tried to add this grid to form using form.control.add(dGrid). It did not let me as I have <% %> code restriction. Which is requirement so I can not get rid of it.
Use Bind() method after datagrid is loaded, which ofcourse give me no values on excel.
Tried to use master page to findcontrol on run time from the loaded page. But still it says should be under tag with property runat=Server.
So Question Is : how to use the master page tag at the child (in Contentplaceholder)

ASP.NET Rendering usercontrols with codebehind

I want to render a usercontrol dynamicly but my code doesn't work as expected. The codebehind won't be executed. Here is my code for rendering:
Dim ucControl As UserControl = LoadControl(pControl.VirtualPath & "/" & Control & ".ascx")
Dim ucSB As New StringBuilder
Dim ucSW As New StringWriter(ucSB)
Dim ucHTML As New HtmlTextWriter(ucSW)
ucControl.RenderControl(ucHTML)
Thank you for your help!
When rendering a UserContorl the normal lifecycle events are not called. This behavior is by design.
You could cast the UserControl to your type and call the methods explicitly:
Dim ucControl As MyUserControl = Ctype(LoadControl(pControl.VirtualPath & "/" & Control & ".ascx"), MyUserControl)
ucControl.Page_Load(me, EventArgs.Empty)
Another option is to add the dyncamically loaded control to your page as early as possible in the page lifecycle, so that the event wil be called.

Accessing server-side control by its ID property in ASP.net

On my default.aspx page I have a bunch of divs with an ID and runat="server":
<div id="serverOne" runat="server"></div>
<div id="serverTwo" runat="server"></div>
<!--etc...-->
In my code behind I've declared a multidimensional array (or grid) with 2 values -- the first being an IP address and the second the server name.
Dim servers = {{"10.0.0.0", "serverOne"}, {"10.0.0.1", "serverTwo"}}
My question is, is there a way where I can target my divs from my code behind using a value from the array?
For i As Integer = 0 To 1
'This is what I want it to do:
servers(i, 1).InnerHtml = "<span>Testing " & servers(i, 1) & "</span>"
Next
You can do this using the FindControl method on the page. However, out of the box FindControl looks only at the first level of children, and does not go into the childrens' children. In order to handle this you need to use a helper method that allows FindControl to recursively search through the control hierarchy to find the one you want. Add this method to your code behind, or some shared class that multiple pages can access:
Protected Function FindControlRecursive(control As Control, id As String)
If (control.ID = id) Then
Return control
End If
For Each ctl In control.Controls
Dim foundControl = FindControlRecursive(ctl, id)
If (foundControl IsNot Nothing) Then
Return foundControl
End If
Next
Return Nothing
End Function
Once you have that, it's pretty easy to find your <div> just by using the string ID property.
For i As Integer = 0 To 1
Dim div = CType(FindControlRecursive(Me, servers(i, 1)), HtmlGenericControl)
div.InnerHtml = "<span>Testing " & servers(i, 1) & "</span>"
Next
Reference: http://forums.asp.net/t/1107107.aspx/1

Loading usercontrol to string and submitting the form within

What i'm doing is creating a website where the design is done i html files that are then read into the masterpage using System.IO.StreamReader.
and inside the html templates there are keywords like #USER.LOGIN#
that I replace with functions etc.
The issue is that i'm replacing #USER.LOGIN# With a usercontrol where there is a login form.
I have a function that reads the usercontrol into a string and it works.
but since the usercontrol is loaded to string alle the events are not following.
so when I submit the login form nothing nothing happends (the page posts) but cannot get any of the fields from the form...
NOTE:
i'm using url-rewriting so urls are http://www.domain.com/account/login
where account is account.aspx and login is the mode the account is in.
Code for replacing the keyword in the streamreader loop (pr line)
If InStr(line, "#USER.LOGIN#") Then
line = line.Replace("#USER.LOGIN#", vbCrLf & userfunc.GetMyUserControlHtml("uc", "account_login.ascx", "/account/login/") & vbCrLf)
End If
And the functions to read usercontrol
Public Shared Function GetMyUserControlHtml(contextKey As String, controllerfile As String, Optional ByVal formaction As String = "")
Dim myId As Guid = New Guid()
Return userfunc.RenderUserControl("~\Controllers\" & controllerfile, "", myId, formaction)
End Function
Public Shared Function RenderUserControl2(path As String, Optional ByVal formaction As String = "") As String
Using pageHolder As New Page(), _
viewControl As UserControl = DirectCast(pageHolder.LoadControl(path), UserControl), _
output As New StringWriter(), _
tempForm As New HtmlForm()
If formaction <> "" Then
tempForm.Action = formaction
Else
tempForm.Action = HttpContext.Current.Request.RawUrl
End If
tempForm.Controls.Add(viewControl)
pageHolder.Controls.Add(tempForm)
HttpContext.Current.Server.Execute(pageHolder, output, False)
Dim outputToReturn As String = output.ToString()
Return outputToReturn
End Using
End Function
How would you guyz do this?
I need the userlogin to be hardcoded in the usercontrol but still be able to place it anywhere using the template keyword.
This will also be used with other functions (newsletter signup, shoutbox etc.)
what i would suggest is register you control on the web config..
<add tagPrefix="CustomControl" tagName="LogIn" src="~/UserControls/Login.ascx"/>
you can still use "#USER.LOGIN#" but instead of replacing it with a control...
replace it with a something like this
<CustomControl:LogIn id="LogIn" runat="server"/>
this is just a quick write up.. but you could always try if it works
you can save your HTML like this istead of placing an actual "#USER.LOGIN#"
<% =GetLoginControl() %>
and then create a public function in your code behind named GetLoginControl() and return a response.write of the HTML Mark up you need

Resources