Page_PreRender finding div by id (asp.net VB) - asp.net

I am trying to run some code on Page_PreRender but only want it to run on hyperlinks within a certain DIV.
What the code does is change the colour of a hyperlink if the NavigateUrl = the URL of the page the user is on.
I have some code that works but it changes the colour of every link on the page that matches when I only want it to happen within a certain div.
The DIV ID i want the hyperlinks changed in is 'subNav'
CURRENT CODE
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim filePath As String = "/~" & System.Web.HttpContext.Current.Request.Path
Dim strControlType As String
For Each ctrl As Control In Me.Controls
For Each subctrl As Control In ctrl.Controls
strControlType = Convert.ToString(subctrl.[GetType]())
If strControlType = "System.Web.UI.WebControls.HyperLink" Then
If filePath = "/" & DirectCast(subctrl, HyperLink).NavigateUrl Then
'DirectCast(subctrl, HyperLink).CssClass = "active"
DirectCast(subctrl, HyperLink).Attributes.Add("style", "color:#993366")
'Label2.Text = "/" & DirectCast(subctrl, HyperLink).NavigateUrl
End If
End If
Next
Next
End Sub
CODE IM TRYING
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim filePath As String = "/~" & System.Web.HttpContext.Current.Request.Path
Dim strControlType As String
Dim subNavDiv As HtmlControl = CType(FindControl("subNav"), HtmlControl)
For Each ctrl As Control In subNavDiv.Controls
For Each subctrl As Control In ctrl.Controls
strControlType = Convert.ToString(subctrl.[GetType]())
If strControlType = "System.Web.UI.WebControls.HyperLink" Then
If filePath = "/" & DirectCast(subctrl, HyperLink).NavigateUrl Then
'DirectCast(subctrl, HyperLink).CssClass = "active"
DirectCast(subctrl, HyperLink).Attributes.Add("style", "color:#993366")
'Label2.Text = "/" & DirectCast(subctrl, HyperLink).NavigateUrl
End If
End If
Next
Next
End Sub
Not sure if this is the way to go about it or not, but it doesn't seem to be working.
Thanks for any help.
J.

You will need to add a runat="server" tag to the div and give it an ID. Once you do that, you can find the DIV like this:
EDIT: Use Panel instead of DIV, and add HyperLink controls to the Panel, like this:
<asp:Panel ID="pnlLinks" runat="server">
<asp:HyperLink ID="lnk1" runat="server" Text="Link 1" />
<asp:HyperLink ID="lnk2" runat="server" Text="Link 2" />
</asp:Panel>
Then in your code behind, do this:
For Each lnk As HyperLink In pnlLinks.Controls.OfType(Of HyperLink)()
lnk.NavigateUrl = "/somefolder/somepage.aspx"
Next
UPDATE
I added in some code when iterating through the links:
Response.Write(DirectCast(subctrl, HyperLink).NavigateUrl & "<br />")
But when I added runat="server" to the div the hyperlinks I within the div were no longer writen out.
UPDATE2
Got there with your help, the panel bit definitely worked, thanks.
Final Code:
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim filePath As String = "/~" & System.Web.HttpContext.Current.Request.Path
For Each lnk As HyperLink In subNav.Controls.OfType(Of HyperLink)()
If filePath = "/" & lnk.NavigateUrl Then
DirectCast(lnk, HyperLink).CssClass = "active"
End If
Next
End Sub

Related

Add click event to dynamic button inside calendar

I have a calendar control in my website (vb.net in asp.net)(the standard calendar control but I manipulated it and now it looks like outlook calendar)
The events are added to the calendar as dynamic buttons, and each button has uniqe ID which is the same even after postback.
This is my code to generate the button and add it to the appropiate cell in calendar:
Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender
Dim nextDate As DateTime
If Not dsHearings Is Nothing Then
For Each dr As DataRow In dsHearings.Tables(0).Rows
nextDate = CType(dr(6), DateTime)
If nextDate = e.Day.Date Then
e.Cell.BackColor = System.Drawing.Color.LightGoldenrodYellow
Dim btn As New Button
btn.Text = Left(dr(7).ToString, 5) & "-" & "جلسة في ملف" & dr(1) & " " & dr(2) & " (" & dr(8) & ")"
btn.CssClass = "CalendarHearingEvent"
btn.BackColor = Drawing.Color.Red
btn.ToolTip = "جلسة في ملف" & dr(1) & " " & dr(2) & " (" & dr(8) & ")"
btn.ID = "btnHearings" & dr(9).ToString
btn.UseSubmitBehavior = True
AddHandler btn.Click, AddressOf Me.HearingButton_Click
Dim lbl As New Label
lbl.Text = "<br>"
e.Cell.Controls.Add(lbl)
e.Cell.Controls.Add(btn)
End If
Next
End If
And this is the Handling sub:
Private Sub HearingButton_Click(sender As Object, e As EventArgs)
End Sub
Everything is perfect, but the click event not firing
Please Help
I used LinkButton, and have set href property of link button to
lnkButton.Attributes("href") = e.SelectUrl
Code
lnkButton = New LinkButton()
lnkButton.CommandArgument = objScheduleDetail.SelectedDate
lnkButton.Text = <Write your text here>
lnkButton.ID = "lnkView" ' you can make it unique as well
lnkButton.Attributes("href") = e.SelectUrl
e.Cell.Controls.Add(lnkButton)
Now when this link button is clicked Calendar.SelectionChanged event is fired. and I use Calendar1.SelectedDate to get the date of the clicked button.
Protected Sub Calendar1_SelectionChanged(sender As Object, e As System.EventArgs) Handles Calendar1.SelectionChanged
Calendar1.SelectedDate ' date which is clicked.
End Sub
Thanks danish for your answer, but I need also to pass arguments. so I used your answer with extra code to meet the needs of my app.
The problem is that when a dynamic button inside calendar is clicked, it posts back the calendar event and not the button click event, so the app is not catching the button.
To bypass that, In my code behind I generated a linkbutton like this:
Dim btn As New LinkButton
btn.Text = "Text On LinkButton"
btn.CssClass = "CalendarEvent"
btn.ToolTip = "What ever"
btn.ID = "LinkButton1"
Dim str As String = "return EventonMyClientClick(" + dr(0).ToString + ");"
btn.OnClientClick = str
e.Cell.Controls.Add(btn)
This will generate a linkbutton inside calendar cell with OnClientClick pointing to a javascript function in HTML Code which goes like this:
<asp:LinkButton ID="LinkButton1" style="display:none;" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
<asp:HiddenField ID="hdEventSentId" runat="server" />
<script>
function EventonMyClientClick(val) {
document.getElementById('<%=hdEventSentId.ClientID%>').value = val;
var btn = document.getElementById('<%=LinkButton1.ClientID%>');
btn.click();
}
</script>
As you see, The dynamic linkbutton passes my argument (dr(0).ToString) to eventonmyclientclick function. the function gets the argument, saves it in the hiddenfield and then perform a click event for the linkbutton1 linkbutton.
the page posts back and catches the linkbutton1 click event, which calls the code behind handler of the linkbutton that handles the argument saved in the hiddenfield:
Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)
Try
Dim EventId As String = hdEventSentId.Value
....
Catch ex As Exception
End Try
End Sub
I hope this will help others seeking for a solution for the same problem.

how to check selected item in Check Box List (generated from code)

i have I have an ASP.NET / VB application
i need check on selected item in check box list but the checkbox is dynamically from code behind
<asp:Panel ID="panel1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Save" />
<asp:Label ID="lbl_Selected_Items" runat="server" Text=""></asp:Label>
</asp:Panel>
code behind
page load
Dim CheckBoxList As New CheckBoxList
pagerview.Controls.Add(CheckBoxList)
...est
Button1 Click event
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CheckBoxList1 As CheckBoxList = CType(Me.FindControl("CheckBoxList"), CheckBoxList)
Dim sCheckedValue As String = ""
For Each oItem As ListItem In CheckBoxList1.Items
If oItem.Selected Then
If sCheckedValue = "" Then
sCheckedValue = ("Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
Else
sCheckedValue += ("<br/>Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
End If
End If
Next
lbl_Selected_Items.Text = sCheckedValue
error text : null reference exception object reference not set to an instance of an object –
Error
So what is happening? Error? no result?
At this point the only thing I can recommend is loading dynamic controls in the page init instead of the page load.
EDIT
You will find when you debug that your checkbox on the first line of your button click is Nothing. There are two mistakes in your code.
When you add the control to the form, you do not provide an id value. and you do not lookup this value
When you lookup the control in the button click FindControl only looks in a single container. It is not recursive. You should be calling pagerView.FindControl
The Page load (I still recommend init):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Handles Me.Load
Dim CheckBoxList As New CheckBoxList
CheckBoxList.ID = "cbl1"
pagerview.Controls.Add(CheckBoxList)
End Sub
And the button click:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CheckBoxList1 As CheckBoxList = CType(pagerview.FindControl("cbl1"), CheckBoxList)
Dim sCheckedValue As String = ""
For Each oItem As ListItem In CheckBoxList1.Items
If oItem.Selected Then
If sCheckedValue = "" Then
sCheckedValue = ("Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
Else
sCheckedValue += ("<br/>Selected Value : " + oItem.Value & " Selected Text: ") + oItem.Text
End If
End If
Next
lbl_Selected_Items.Text = sCheckedValue
End Sub
MS Reference

generate html/asp dynamically

I have a treeview type structure of folders/links that's populated from a table. What I was attempting to do was procedural loop through my recordset and generate my html in page_init and then try and bind the controls. When I try to add the link buttons to the placeholders in html, it can never seem to find them.
I might be missing something fundamental here, all the examples i've seen bind a control thats already on the page, am I unable to generate the html myself in page_init?
example
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
content_div.Innerhtml = "<asp:PlaceHolder id=""test"" runat=""server"" ></asp:PlaceHolder>"
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim _linkb As New LinkButton
_linkb.ID = "lb_cat_" & cat.uID
_linkb.Attributes.Add("href", "javascript: sltoggle('cat_" & cat.uID & "');")
_linkb.Attributes.Add("Text", "Expand/Close")
_linkb.Attributes.Add("runat", "server")
Dim ph As PlaceHolder = DirectCast(TRIEDEVERYTHINGUNDERTHESUN.FindControl("test"), PlaceHolder)
ph.Controls.Add(_linkb)
End Sub
If someone could point me in the right direction it'd be much appreciated
Regards,
Pete
UPDATE - full code
Private Sub load_dynamic_file_view()
Dim _sb As New StringBuilder
Dim _sfc As New sf_file_category, _sff As New sf_file
_lsfc = _sfc.get_all_sf_file_category
_lsff = _sff.get_active_sf_files
Dim _list_root As List(Of sf_file_category) = _lsfc.FindAll(Function(p) p.parent_id = 0)
If Not _list_root Is Nothing Then
_sb.Append("<strong>File Downloads</strong><br />")
_sb.Append("<div class=""indent-me"" ><br />")
For Each cat As sf_file_category In _list_root
'header/Open Link
Dim _linkb As New LinkButton
_linkb.ID = "lb_cat_" & cat.uID
_linkb.Attributes.Add("href", "javascript: sltoggle('cat_" & cat.uID & "');")
_linkb.Attributes.Add("Text", "Expand/Close")
_linkb.Attributes.Add("runat", "server")
Dim ph As PlaceHolder = DirectCast(Me.Master.FindControl("lb_cat_" & cat.uID), PlaceHolder)
ph.Controls.Add(_linkb)
_sb.Append(HtmlDecode(cat.name) & " <Asp:PlaceHolder id=""lb_cat_" & cat.uID & """ runat=""server"" /><br />")
'_sb.Append("<div id=""cat_" & cat.uID & """ class=""toggle-hide"">")
'_sb.Append(add_child_folder(cat.uID, content))
'_sb.Append(show_files(cat.uID, content))
'_sb.Append("</div><div class=""clearfix"" />")
Next
_sb.Append("</div>")
_sb.Append("<br /><br />")
End If
content_div.InnerHtml = _sb.ToString
End Sub
Private Function add_child_folder(ByVal catid As Long, ByRef content As ContentPlaceHolder) As String
Dim _sb As New StringBuilder
Dim _cl As List(Of sf_file_category) = _lsfc.FindAll(Function(p) p.parent_id = catid)
If Not _cl Is Nothing Then
_sb.Append("<div class=""indent-me"" ><br />")
'For Each _c As sf_file_category In _cl.OrderBy(Function(p) p.view_order)
_cl.Sort(Function(c1 As sf_file_category, c2 As sf_file_category)
Return c1.view_order.CompareTo(c2.view_order)
End Function)
For Each cat As sf_file_category In _cl
Dim _linkb As New LinkButton
_linkb.ID = "lb_cat_" & cat.uID
_linkb.Attributes.Add("href", "javascript: sltoggle('cat_" & cat.uID & "');")
_linkb.Attributes.Add("Text", "Expand/Close")
_linkb.Attributes.Add("runat", "server")
Content.Controls.Add(_linkb)
_sb.Append(HtmlDecode(cat.name) & " <Asp:LinkButton id=""lb_cat_" & cat.uID & """ runat=""server"" Text=""Expand/Close"" href='javascript: sltoggle('cat_" & cat.uID & "');' /><br />")
'_sb.Append("<div id=""cat_" & cat.uID & """ class=""toggle-hide"">")
_sb.Append(add_child_folder(cat.uID, content))
_sb.Append(show_files(cat.uID, content))
'_sb.Append("</div><div class=""clearfix"" >")
Next
_sb.Append("</div><br />")
End If
Return _sb.ToString
End Function
Private Function show_files(ByVal catid As Long, ByRef content As ContentPlaceHolder) As String
Dim _sb As New StringBuilder
Dim _fl As List(Of sf_file) = _lsff.FindAll(Function(p) p.file_category = catid)
If Not _fl Is Nothing Then
_sb.Append("<div class=""indent-me"" ><br />")
For Each _f As sf_file In _fl
Dim _linkb As New LinkButton
_linkb.ID = "file_" & _f.uID
_linkb.Attributes.Add("onCommand", "download_file")
_linkb.Attributes.Add("CommandArgument", _f.uID.ToString)
_linkb.Attributes.Add("Text", _f.file_name)
_linkb.Attributes.Add("runat", "server")
AddHandler _linkb.Command, AddressOf download_file
content.Controls.Add(_linkb)
_sb.Append("<asp:LinkButton id=""file_" & _f.uID & """ runat=""server"" onCommand=""download_file"" commandArgument=""" & _f.uID & """ Text=""" & _f.file_name & """ /><br />")
Next
_sb.Append("</div><br />")
End If
Return _sb.ToString
End Function
What your full code shows is that your building a massive string of HTML. This is fine for some smaller situations, but your code is clearly getting quite big now, and I would suggest you change this approach.
I would recommend that you declare web control equivalents, such as:
new HtmlGenericControl("div") instead of <div></div>
OR
new HtmlAnchor() OR new LinkButton() instead of <a></a>
In the example of a tree structure the HTML may look like this:
<ul>
<li>
ROOT
<ul>
<li>
LEVEL 1
</li>
</ul>
</li>
</ul>
To generate this in code you would do something similar to:
'Menu Holder
Dim treeStruct As HtmlGenericControl("ul")
'Root
Dim branch As HtmlGenericControl("li")
Dim branchItem as HtmlAnchor("a")
'Level 1
Dim subLevel As HtmlGenericControl("ul")
Dim subBranch As HtmlGenericControl("li")
Dim subBranchItem as HtmlAnchor("a")
'Setup Level 1
subBranchItem.InnerText = "LEVEL 1"
subBranchItem.Href = "levelone"
subBranch.Controls.Add(subBranchItem)
subLevel.Controls.Add(subBranch)
'Setup Root
branchItem.InnerText = "ROOT"
branchItem.Href = "root.htm"
'Add Link To Root
branch.Controls.Add(branchItem)
'Add Sub Branch To Root
branch.Controls.Add(subLevel)
treeStruct.Controls.Add(branch)
Important The code above is just for examples sake, ideally you would separate the functionality into functions for branch creation and then loop through your elements with your for loop.
You will also notice that I have used an <UL> instead of <DIV> as I would consider a tree structure to be an un-ordered list. Plus, you will also get the styling benefit from this more ridged structure.
I hope this helps
You generate only HTML tags and do not generate ASP.Net tags, as they can't be parsed by browser.
I think your code should be like
content_div.Innerhtml = "<div id='test'></div>"
ASP:Placeholder control is just a place holder and it is not equal to div HTML tag.
For an example i gave div tag here.
asp.net controls added as text are not known to the page and thus no viewstate / object is stored for it, thus you can never find it using Findcontrol.
Use the object of the control and add it to the parent control's Control collection
e.g.
div.Controls.Add(new PlaceHolder() { ... });
Once you have added it before Render event , its state will be saved and accessable.
It looks like your trying to add a placeholder to the content_div, however, what you are doing is rendering the tag as HTML content.
I don't know exactly what type of control content_div is, but can't you try:
content_div.controls.add(new placeholder() { ID = "test" });
This would then allow you to find the control within the content_div control.
However, what would probably be a much more concise solution for you might be the following:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim _linkb As New LinkButton
_linkb.ID = "lb_cat_" & cat.uID
_linkb.Attributes.Add("href", "javascript: sltoggle('cat_" & cat.uID & "');")
_linkb.Attributes.Add("Text", "Expand/Close")
//you don't need this when using code behind
//_linkb.Attributes.Add("runat", "server")
//this will add your linkbutton to the content_div control
content_div.Controls.Add(_linkb)
End Sub
Give this ago and you should find it to be a useful way of dynamically building your page with asp controls.

How can i scroll to an anchor?

I have bound a datapager control to a listview.
I would like to scroll to the first item of the listview control on the DataPager click. I think this should be done with javascript. It seems that the datapager does not allow that.
What options do I have? How can I scroll to a specific anchor when clicking on the DataPager?
you can use the basic html named anchor to scroll to a specific anchor.
You can use the javascript function scrollIntoView for that on client side or on "server side":
http://www.codeproject.com/KB/aspnet/ViewControl.aspx
Thanks Tim!
And for the lazy guys out there (just like me ;), here is the VB.NET equivalent.
It contains typo corrections and the new RegisterClientScriptBlock Method
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
FocusControlOnPageLoad("Label1", Me.Page)
End Sub
Public Sub FocusControlOnPageLoad(ByVal ClientID As String, ByVal page As System.Web.UI.Page)
Dim csName As String = "ScrollViewScript"
Dim csType As Type = Me.GetType
Dim cs As ClientScriptManager = page.ClientScript
If Not cs.IsClientScriptBlockRegistered(csType, csName) Then
Dim csText As New StringBuilder()
csText.Append("<script>function ScrollView(){")
csText.Append("var el = document.getElementById('" & ClientID & "');")
csText.Append("if (el != null){")
csText.Append("el.scrollIntoView();")
csText.Append("el.focus();}}")
csText.Append("window.onload = ScrollView;")
csText.Append("</script>")
cs.RegisterClientScriptBlock(csType, csName, csText.ToString())
End If
End Sub

Pass values from QueryString parameter in GridView hyperlink

I'm using GridView with a HyperLink column, and I want to do the following:
<asp:HyperLinkField DataNavigateUrlFields="DID"
DataNavigateUrlFormatString="~/student/group/document/Body.aspx?DID={0}&GN={QueryString("GN")}" HeaderText="View Document" Text="view" />
How I can retrieve the value of GN from the QueryString parameter and add it to the HyperLink column ?
How important is it to you to do this in the markup? I'm fairly sure you can't do this in the markup with the DataNavigateUrlFields and DataNavigateUrlFormatString, but you can do it in code in the RowDataBound event:
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim link As HyperLink
Dim row As DataRow
If e.Row.RowType = DataControlRowType.DataRow Then
'Get the row we are binding to
row = CType(e.Row.DataItem, DataRowView).Row
'Find the hyperlink control we want to set the link for
link = CType(e.Row.Controls(1).Controls(0), HyperLink)
'Check if the querystring we want to include is missing or empty
If Request.QueryString("GN") Is Nothing Or Request.QueryString("GN") Is String.Empty Then
'If there is no querystring then we can only bind to the DID
link.NavigateUrl = "~/student/group/document/Body.aspx?DID=" & row.Item("DID").ToString
Else
'The querystring element is present so include it in the link
link.NavigateUrl = "~/student/group/document/Body.aspx?DID=" & row.Item("DID").ToString & "&GN=" & Request.QueryString("GN").ToString
End If
End If
End Sub

Resources