Regarding itemdatabound in repeater - asp.net

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

Related

How do I get last modified date of website

I have website URL's in a DataGridView Cell when I click on the Cell the website is loaded in Chrome. I am using VS 2019 and VB.Net only I do not have ASP.Net installed.
I have tried a bunch of different concepts from some SO post that go back to 2011
With very little success I found one function that looked workable but no results I will post that code.
My question is How do I get last modified date of website?
If using VB.Net ONLY is not workable point me to a reference for other tools needed.
Public Property DateTime_LastModified As String
Dim webPAGE As String
This code is inside a click event for the DataGridView
ElseIf gvTxType = "View" Then
webPAGE = row.Cells(2).Value.ToString()
'Modified: <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Process.Start(webPAGE)
GetDateTimeLastModified(requestUriString)
Label1.Text = DateTime_LastModified
'Dim strPath As String = webPAGE + "javascript : alert(document.lastModified)"
'Dim strPath As String = Request.PhysicalPath
'Server.MapPath
'Label1.Text = System.IO.File.GetLastWriteTime(webPAGE).ToString()
'Label1.Text = strPath '"Modified: " + System.Web.UI.GetLastWriteTime(strPath).ToString()
'Label1.Text = strPath + "Modified:" + System.MapPath.Request.ServerVariables.Get("SCRIPT_NAME")
'Process.Start(webPAGE)
Here is the Edit I tried from the Answer
Public Class GetURLdate1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strURL As String
strURL = TextBox1.Text
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head, strURL)
Dim resp = client.SendAsync(msg).Result
Dim strLastMod As String = resp.Content.Headers.LastModified.ToString
MsgBox("Last mod as string date" & vbCrLf & strLastMod)
'Dim lastMod As DateTime = CDate(strLastMod)
'MsgBox(lastMod)
End Sub
Private Sub GetURLdate1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "https://www.youtube.com/c/stevinmarin/videos"
'"https://stackoverflow.com/questions/70825821/how-do-i-get-last-modified-date-of-website"
End Sub
Returns NO Value for strLastMod
Ok, so it not clear if you need a routine to go get all the URL's in the grid, and update the last updated for each site/url?
Or are you looking to ONLY update the site WHEN you click on the button to jump to the site?
It is easy to do both.
I mean, say we have this markup - drop in a gridview (I let the wizards created it).
I then blow out the datasoruce control, and then remove the data soruce ID setting from the GV
So, I have this markup:
<div style="padding:35px">
<asp:GridView ID="GridView1" runat="server" CssClass="table" Width="65%"
AutoGenerateColumns="False" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="Url" HeaderText="Url" ItemStyle-Width="500" />
<asp:BoundField DataField="LastUpDated" HeaderText="Last UpDated" />
<asp:BoundField DataField="LastVisit" HeaderText="Last Visit" />
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="cmdJump" runat="server" Text="View" CssClass="btn"
OnClick="cmdJump_Click"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="cmdGetAll" runat="server" Text="Upate all Last updated" CssClass="btn" />
</div>
Ok, and my code to load the gv is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL = New SqlCommand("SELECT * FROM tblSites", conn)
Dim rstData As New DataTable
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
And now we have this:
Ok, so just dropped in a plane jane button into the GV. When I click on that button, I will update the last visit - not clear if you ALSO want this to update the last update for the given url?
we can do both.
So, out simple button we dropped? Well, lets have it update the last time we visit (click) to jump to the site).
Protected Sub cmdJump_Click(sender As Object, e As EventArgs)
Dim cmdView As Button = sender
Dim gRow As GridViewRow = cmdView.NamingContainer
Dim PKID As Integer = GridView1.DataKeys(gRow.RowIndex).Item("ID")
' udpate with last visit click
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL = New SqlCommand("update tblSites SET LastVisit = #Visit WHERE ID = #ID", conn)
conn.Open()
cmdSQL.Parameters.Add("#Visit", SqlDbType.DateTime).Value = Date.Now
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID
cmdSQL.ExecuteNonQuery()
End Using
End Using
' Now jump to that url
Response.Redirect(gRow.Cells(0).Text)
End Sub
And the button to go fetch and update all last updates (every row) of the given URL's cna be this:
Protected Sub cmdGetAll_Click(sender As Object, e As EventArgs) Handles cmdGetAll.Click
Using conn = New SqlConnection(My.Settings.TEST4)
Using cmdSQL = New SqlCommand("SELECT * FROM tblSites", conn)
Dim rstData As New DataTable
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
For Each OneRow As DataRow In rstData.Rows
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head, OneRow("Url").ToString)
Dim resp = client.SendAsync(msg).Result
Dim lastMod As DateTimeOffset? = resp.Content.Headers.LastModified
OneRow("LastUpDated") = lastMod.Value.ToString
Next
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
da.Update(rstData)
' now re-load grid
LoadGrid()
End Using
End Using
End Sub
So, the above has the code to update the data for all URL's.
But, your question seems to suggest that when you click on the GV row button, you ALSO want to get/save/update the given row of the GV with the last update information from the web site url?
Ok, then, we modify our click code, to update both our last click visit, and then also get that web site last update information.
So, just change the button click row code to this then:
Protected Sub cmdJump_Click(sender As Object, e As EventArgs)
Dim cmdView As Button = sender
Dim gRow As GridViewRow = cmdView.NamingContainer
Dim PKID As Integer = GridView1.DataKeys(gRow.RowIndex).Item("ID")
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head, gRow.Cells(0).Text)
Dim resp = client.SendAsync(msg).Result
Dim lastMod As DateTime = resp.Content.Headers.LastModified.ToString
' udpate with last visit click, and also get laste update from web site
Using conn = New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
"update tblSites SET LastVisit = #Visit,LastUpdated = #LastUpDate WHERE ID = #ID"
Using cmdSQL = New SqlCommand(strSQL, conn)
conn.Open()
cmdSQL.Parameters.Add("#Visit", SqlDbType.DateTime).Value = Date.Now
cmdSQL.Parameters.Add("#LastUpDate", SqlDbType.DateTime).Value = lastMod
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID
cmdSQL.ExecuteNonQuery()
End Using
End Using
' Now jump to that url
Response.Redirect(gRow.Cells(0).Text)
End Sub
Edit: Not using asp.net
I now see in your post that you suggest you are not using asp.net. However, the above code would work near the same if you are say using a vb.net desktop + gridview. In other words, the code should be similar, and that includes the code to get that web site date.
so, you need to use follow hyper link, but the code to get the date from the web site, and even your general form layout for desktop. The results - even the way your gird looks will thus be very similar to the above web page, the overall idea here thus applies equal well to desktop or web based. I mean, if you have visual studio installed, then you could try above - as VS does install the web bits and parts for you.
Edit #2 - code to get last modified date.
There is NOT some process start, NEVER suggested to use as such. The code you need is thus this:
webPAGE = row.Cells(2).Value.ToString()
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head,webPAGE)
Dim resp = client.SendAsync(msg).Result
Dim lastMod As DateTime = resp.Content.Headers.LastModified.ToString
MsgBox("DATE " & lastMod)
Edit#3: Code as win forms
Ok, so we create a blank new windows form.
Drop in a text box, drop in a button.
We have this code:
Imports System.Net.Http
Public Class GetURLdate1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strURL As String
strURL = TextBox1.Text
Dim client = New HttpClient()
Dim msg As New HttpRequestMessage(HttpMethod.Head, strURL)
Dim resp = client.SendAsync(msg).Result
Dim strLastMod As String = resp.Content.Headers.LastModified.ToString
MsgBox("Last mod as string date" & vbCrLf & strLastMod)
Dim lastMod As DateTime = strLastMod
MsgBox(lastMod)
End Sub
Private Sub GetURLdate1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text =
"https://stackoverflow.com/questions/70825821/how-do-i-get-last-modified-date-of-website"
End Sub
So, I used THIS web page for the url.
When I run this form - click on button, I see this:

Repeater Control paging error

I'm trying to create a pager in a repeater control. The content is being pulled from the database and is displaying but when I click on the previous and next buttons they don't page, that is, I stay on the same content. Would anyone be able to see the error from the code below? No errors or showing so I think it is something minor but I have been banging my head against a wall trying to find it
Markup:
<asp:Repeater ID="ArtRepeater" runat="server">
<HeaderTemplate>
<h2>Items in Selected Category:</h2>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="HyperLink"
NavigateUrl='<%# Eval("MovieID", "Default2.aspx?ArtID={0}")%>'>
<%# DataBinder.Eval(Container.DataItem, "MovieTitle")%>
</asp:HyperLink>
</li>
</ItemTemplate>
Code Behind:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
Server.MapPath("/App_Data/MovieBoard.accdb"))
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT MovieID, MovieTitle FROM Movies", strConnect)
objOleDBAdapter.Fill(DS, "Movies")
Return DS.Tables("Movies").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 1
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
End Sub
After banging my head against a wall I found a solution. I forgot to connect the buttons to the repeater control. Here's a solution:
Imports System.Data
Imports System.Data.OleDb
Partial Class Default2
Inherits System.Web.UI.Page
Dim pagedData As New PagedDataSource
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
Server.MapPath("/App_Data/MovieBoard.accdb"))
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT MovieID, MovieTitle FROM Movies", strConnect)
objOleDBAdapter.Fill(DS, "Movies")
Return DS.Tables("Movies").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 1
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (Not pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
If Not pagedData.IsFirstPage Then
btnPrev.PostBackUrl = Request.CurrentExecutionFilePath + _
"?Page=" + CStr(pagedData.CurrentPageIndex - 1)
End If
If Not pagedData.IsLastPage Then
btnNext.PostBackUrl = Request.CurrentExecutionFilePath + _
"?Page=" + CStr(pagedData.CurrentPageIndex + 1)
End If
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()

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.

ASP.NET, VB.NET, and Database Issue

I am trying to learn how to do this .NET frameworks for my job and what not..... I can't figure why it isn't working.
Error occurs here:
myCommand.Connection.Open()
I am assuming it is because of how I am doing....
Dim idbox As TextBox = E.Item.Cells(numCols - 1).Controls(0)
myCommand.Parameters("#Id").Value = Integer.Parse(idbox.Text)
Source:
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Data.OleDb" %>
<html>
<script language="VB" runat="server">
Dim myConnection As SqlConnection
' Create a connection to the "pubs" SQL database located on the
' local computer.
Sub Page_Load(Src As Object, E As EventArgs)
If Session("Admin") <> True Then
Response.Redirect("login.aspx")
Else
Dim myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")
' Determine whether this page is a postback. If it is not a
' postback, call BindGrid.
If Not IsPostBack Then
Dim dbconn As OleDbConnection
Dim sql As String
Dim dbcomm As OleDbCommand
Dim dbread As OleDbDataReader
dbconn = New OleDbConnection("CONNECTION INFO")
dbconn.Open()
sql = "SELECT Name FROM TestData"
dbcomm = New OleDbCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader()
DropDownList1.Items.Clear()
While dbread.Read
DropDownList1.Items.Add(dbread(0))
End While
dbread.Close()
dbconn.Close()
BindGrid()
End If
End If
End Sub
' Create an index to the DataGrid row that is clicked and
' call BindGrid.
Sub MyDataGrid_Edit(sender As Object, E As DataGridCommandEventArgs)
MyDataGrid.EditItemIndex = CInt(E.Item.ItemIndex)
BindGrid()
End Sub
' Cancel resets the index to the row's previous settings.
Sub MyDataGrid_Cancel(sender As Object, E As DataGridCommandEventArgs)
MyDataGrid.EditItemIndex = -1
BindGrid()
End Sub
' When the Update link is clicked, build a SQL UPDATE command,
' connect to the database, update the row's information in the
' database, and rebind the DataGrid to show the updated information.
Public Sub MyDataGrid_Update(sender As Object, _
E As DataGridCommandEventArgs)
Dim updateCmd As String = "UPDATE TestData SET AdoptedNum = #AdoptedNum, PrecinctNum = #PrecinctNum WHERE Id = #Id"
Dim myCommand As SqlCommand = New SqlCommand(updateCmd, myConnection)
myCommand.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
myCommand.Parameters.Add(New SqlParameter("#PrecinctNum", SqlDbType.Int))
myCommand.Parameters.Add(New SqlParameter("#AdoptedNum", SqlDbType.Int))
myCommand.Parameters.Add(New SqlParameter("#Id", SqlDbType.Int))
' Initialize the SqlCommand "#ID" parameter to the ID of the row
' that must be clicked.
Dim numCols As Integer = E.Item.Cells.Count
Dim i As Integer
Dim colvalue As String
Dim txtBox As TextBox
Dim idbox As TextBox = E.Item.Cells(numCols - 1).Controls(0)
myCommand.Parameters("#Id").Value = Integer.Parse(idbox.Text)
' Create an array of column names.
Dim cols() As String = {"#Name", "#PrecinctNum", "#AdoptedNum", "#Id"}
' Skipping the first, second, and last columns, iterate through the
' columns, checking for empty values. If an empty value is found,
' display a message box. Also initialize the SqlCommand
' parameter values.
For i = 2 To numCols - 1
txtBox = E.Item.Cells(i).Controls(0)
colvalue = txtBox.Text
If (i < numCols And colvalue = "") Then
Message.InnerHtml = "ERROR: Null values not allowed for " _
& "Author ID, Name or Phone"
Message.Style("color") = "red"
Exit Sub
End If
myCommand.Parameters(cols(i - 1)).Value = colvalue
Next i
' Connect to the database and update the information.
myCommand.Connection.Open()
' Test whether the data was updated, and display the
' appropriate message to the user.
Try
myCommand.ExecuteNonQuery()
Message.InnerHtml = "<b>Record Updated.</b><br>"
MyDataGrid.EditItemIndex = -1
Catch ex As SqlException
If ex.Number = 2627 Then
Message.InnerHtml = "ERROR: A record already exists" _
& " with the same primary key"
Else
Message.InnerHtml = "ERROR: Could not update record," _
& " please ensure the fields are correctly filled out."
Message.Style("color") = "red"
End If
End Try
' Close the connection.
myCommand.Connection.Close()
' Rebind the DataGrid to show the updated information.
BindGrid()
End Sub
' The BindGrid procedure connects to the database and implements
' a SQL SELECT query to get all the data in the "Authors" tablea.
Public Sub BindGrid()
Dim myConnection As SqlConnection = _
New SqlConnection("CONNECTION INFO")
Dim myCommand As SqlDataAdapter = New SqlDataAdapter("SELECT *" _
& " FROM TestData WHERE Name='" & DropDownList1.SelectedValue & "'", myConnection)
Dim ds As DataSet= New DataSet()
myCommand.Fill(ds)
MyDataGrid.DataSource = ds
MyDataGrid.DataBind()
End Sub
Protected Sub MyDataGrid_SelectedIndexChanged(sender As Object, e As System.EventArgs)
End Sub
Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
BindGrid()
End Sub
</script>
<body style="font: 10pt verdana">
<form id="Form1" runat="server"><center>
<h3><font face="Verdana">Updating a Row of Data.</font></h3>
<span id="Message" EnableViewState="false"
style="font:arial 11pt;" runat="server"/><p>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<ASP:DataGrid id="MyDataGrid" runat="server"
Width="800"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
OnEditCommand="MyDataGrid_Edit"
OnCancelCommand="MyDataGrid_Cancel"
OnUpdateCommand="MyDataGrid_Update"
>
<Columns>
<ASP:EditCommandColumn EditText="Edit" CancelText="Cancel"
UpdateText="Update"/>
</Columns>
</ASP:DataGrid>
</center>
</form>
</body>
</html>
I suspect the problem is you define but never initialize the instance variable myConnection. You define and instantiate a local variable of the same name within the Page_Load function, but that is a distinct and different object than your instance variable.
In your Page_Load, if you change this:
Dim myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")
to this:
myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")
then your instance variable should be initialized and ready for use in your MyDataGrid_Update event handler.
Did this even compile? This wont work because your code has a bug.
SqlCommand won't support myCommand.Connection.Open()

This code will display selected checkboxes text in textbox as 1,2,3,4,5,6,7,8,9

This code will display selected checkboxes Text in textbox as in the order i checked it 1,2,3,4,5,6,7,8,9
But it will not display selected checkboxes Text in textbox after 9
Partial Class _45seater_WebUserControl
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim str As String = Nothing
Dim id As String = Nothing
Dim ch As String = Nothing
For Each ctrl As Control In Panel1.Controls
If ctrl.GetType() Is GetType(CheckBox) Then
Dim chk As CheckBox = ctrl
UpdatePanel1.FindControl("chk")
If chk.Checked = True Then
If TextBox1.Text = "" Then
TextBox1.Text = chk.Text
Else
Dim SearchString As String = chk.Text
id = TextBox1.Text
If id.Contains(SearchString) <> -1 Then
TextBox1.Text = TextBox1.Text + "," + chk.Text
Else
End If
End If
Else
Dim SearchString As String = chk.Text
id = TextBox1.Text
If id.Contains(SearchString) <> -1 Then
Else
id = RemoveSubString(id, chk.Text)
TextBox1.Text = id
End If
End If
End If
Next
End Sub
Private Function RemoveSubString(ByVal stringvalue As String, ByVal stringremove As String) As String
Dim pos As Integer = stringvalue.IndexOf(stringremove)
If pos > 0 Then
Return stringvalue.Remove(pos - 1, stringremove.Length + 1)
ElseIf pos = 0 Then
If stringvalue.Contains(",") <> -1 Then
Return stringvalue.Remove(pos, stringremove.Length)
Else
Return stringvalue.Remove(pos, stringremove.Length + 1)
End If
End If
Return stringvalue
End Function
End Class
can any body show after chekbox10,checkbox11,checkbox12 in text box as 10,11,12 ......so on using this code
I really don't understand that requirement but i think the only thing the function should do is to print the ID's of all checked CheckBoxes in a TextBox.
Why do you complicated it, this works too:
TextBox1.Text = String.Empty
For Each control As Control In form1.Controls
If TypeOf control Is CheckBox AndAlso DirectCast(control, CheckBox).Checked Then
TextBox1.Text &= control.ID & ","
End If
Next
'remove last comma'
If TextBox1.Text.Length <> 0 Then TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)
According to your new informations about the order, try this:
Protected Sub CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chk As CheckBox = DirectCast(sender, CheckBox)
Dim separator As Char = ","c
If TextBox1.Text.Length <> 0 Then
Dim allIIDs As New List(Of String)(TextBox1.Text.Split(separator))
allIIDs.Remove(chk.ID)
If chk.Checked Then
allIIDs.Add(chk.ID)
End If
TextBox1.Text = String.Empty
For Each id As String In allIIDs
TextBox1.Text &= id & separator
Next
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)
Else
TextBox1.Text = chk.ID
End If
End Sub
To register the CheckedChanged-Event on the CheckBoxes you have to add following on aspx for every Checkbox:
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckedChanged" />
or if you are lazy and want to do that in Codebehind, add following in Page_Init:
Private Sub WebForm1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each control As Control In Me.form1.Controls
If TypeOf control Is CheckBox Then
Dim chk As CheckBox = DirectCast(control, CheckBox)
chk.AutoPostBack = True
AddHandler chk.CheckedChanged, AddressOf CheckedChanged
End If
Next
End Sub

Resources