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.
Related
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.
Other than Request.Form("example") which use the name of the textbox. I want to know if there is any other way to get the value rather than using the Request.Form. I hope you guys understand what I mean and I hope this is not a dumb question. As I'm having problem using the name to get the value of what the textbox consist.
So I thought of using the id to get the value do tell me if that could work.And I would also like to know how it works.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
For Each row As DataRow In cardDT.Rows
Literal1.Text += "<tr>"
Literal1.Text += "<td><input type='text' id='test" & i & "' name='test" & i & "' value='" & row("Date") & "' maxlength='20'></td>"
Literal1.Text += "<td><input id='Checkbox1' type='checkbox' name='chk" & i & "' /></td>"
Literal1.Text += "</tr>"
i += 1
Next
Literal1.Text += " </table>"
End Sub
This is the button, for now is just check the value stored in request.form but when I click on this button I receive an error when I used the name:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
Dim i = 0
For Each row As DataRow In EmployeeDt.Rows
Dim t = Request.Form("test" & i)
If Request.Form("check" & i) <> "" Then
MsgBox("check" & i & " " & t)
End If
i += 1
Next
End Sub
There are two ways. You can choose which one suits your needs:
Change your html input control to asp:TextBox control. This will still render in the browser as html input anyways. So it shouldn't make a difference, but you would be able to access it in your code-behind. You can then get its value by ControlId.Text.
Just add the RunAt="Server" attribute on your html input (textbox) control, and you can access it in the code-behind as any other server side control. You can then probably get it value by ControlId.Value.
Here is a script for displaying name of files (for download) in data grid table. Is it possible that to show the latest created file in top row?. Please help.
<%# Import Namespace="System.IO" %>
<script language="VB" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then
Dim dirInfo As New DirectoryInfo("D:\SeverUpload\Safety")
articleList.DataSource = dirInfo.GetFiles("*.*")
articleList.DataBind()
End If
End Sub
Sub articleList_ItemDataBound(sender as Object, e as DataGridItemEventArgs)
' First, make sure we're NOT dealing with a Header or Footer row
If e.Item.ItemType <> ListItemType.Header AND _
e.Item.ItemType <> ListItemType.Footer then
'Now, reference the Button control that the Delete ButtonColumn
'has been rendered to
Dim deleteButton as Button = e.Item.Cells(0).Controls(0)
'We can now add the onclick event handler
deleteButton.Attributes("onclick") = "javascript:return " & _
"confirm('Are you sure you want to delete the file " & _
DataBinder.Eval(e.Item.DataItem, "Name") & "?')"
End If
End Sub
Sub articleList_DeleteFile(sender as Object, e as DataGridCommandEventArgs)
'First, get the filename to delete
Dim fileName as String = articleList.DataKeys(e.Item.ItemIndex)
'lblMessage.Text = "You opted to delete the file " & _
'fileName & ".<br />" & _
'"This file could be deleted by calling: " & _
'"<code>File.Delete(FileName)</code><p>"
'You would want to rebind the Directory's files to the DataGrid after
'deleting the file...
End Sub
</script>
Where is the data being loaded in at? It's possibly to just add a ORDER BY DATETIME DESC when querying the database.
Please use the below in the page load.
If Not Page.IsPostBack then
Dim dirInfo As New DirectoryInfo("D:\SeverUpload\Safety")
Dim files As FileSystemInfo() = dirInfo.GetFileSystemInfos("*.*")
Dim orderedFiles = files.OrderBy(Function(f) f.CreationTime)
articleList.DataSource = orderedFiles
articleList.DataBind()
End If
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
I have following code in page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GetDetails()
PopulateRepeater()
End If
End Sub
Sub PopulateRepeater()
Dim dt As DataTable = GetDetails()
Dim dtDoc As DataTable = objdoc.GetDocDetails(Session("RegID"))
If dtDoc.Rows.Count > 0 Then
Dim strUserName As String = dt.Rows(0)("Name")
Dim files As IList(Of FileInfo) = New List(Of FileInfo)()
Dim filters As String = "*.jpg;*.png;*.gif"
For Each filter As String In filters.Split(";"c)
Dim fit As FileInfo() = New DirectoryInfo(Me.Server.MapPath("../SiteImages/" & strUserName & "/" & Session("RegID") & "/")).GetFiles(filter)
For Each fi As FileInfo In fit
files.Add(fi)
Next
Next
strPath = Server.MapPath("../SiteImages/" & strUserName & "/" & Session("RegID") & "/")
Me.Repeater1.DataSource = files
Me.Repeater1.DataBind()
End If
End Sub
I have following code in itemdatabound
Dim ThViewr As Bright.WebControls.ThumbViewer = DirectCast(e.Item.FindControl("Th1"), Bright.WebControls.ThumbViewer)
Dim dtUser As DataTable = GetDetails()
Dim dtDoc As DataTable = objdoc.GetDocDetails(Session("RegID"))
Dim strUserName As String = dtUser.Rows(0)("Name")
If dtDoc.Rows.Count > 0 Then
For i As Integer = 0 To dtDoc.Rows.Count - 1
Dim ImagePath As String = "../SiteImages/" & strUserName & "/" & Session("RegID") & "/" + dtDoc.Rows(i)("ImageName")
ThViewr.ImageUrl = ImagePath
Next
End If
My aspx contains
<div style="clear:both;">
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<span style="padding:2px 10px 2px 10px">
<bri:ThumbViewer Id="Th1" runat="server" Height="100px" Width="100px"/>
</span>
</ItemTemplate>
</asp:Repeater>
</div>
If the imagePath ="../SiteImages/Ram/PR/First.jpg" Means the folder PR aontains exactly 3 images namely First.jpg,Second.jpg and Third.jpg.
Now with above code three images are coming but Third.jpg is repeating 3 times.First.jpg and Second.jpg is not coming.Can anybody help to resolve this.
The ItemDataBound event is raised once for every object in the bound list, so it will be fired three times in your case; once for each file. You should not loop over your data table, but rather grab the current item from the event args.
Update: looking closer at the code I find it somewhat confusing. You bind a list of FileInfo objects to the repeater, but fetch data from a DataTable when the items are bound. I am guessing that you want to show the files found, and I think that the following code in ItemDataBound will do that for you:
Dim ThViewr As Bright.WebControls.ThumbViewer = DirectCast(e.Item.FindControl("Th1"), Bright.WebControls.ThumbViewer)
Dim dtUser As DataTable = GetDetails()
Dim strUserName As String = dtUser.Rows(0)("Name")
Dim ImagePath As String = "../SiteImages/" & strUserName & "/" & Session("RegID") & "/" + DirectCast(e.Item.DataItem, FileInfo).Name
ThViewr.ImageUrl = ImagePath