Nested Repeaters Asp .NET ItemDataBound not called? - asp.net

I am trying to nest 2 repeaters. 2nd repeater is data bound on first repeater's itemDataBind event.
<asp:Repeater ID="FolderRepeater" runat="server" OnItemDataBound="CategoryRepeater_ItemDataBound">
<ItemTemplate>
<p><%# Container.DataItem("DocumentName")%></p>
<asp:Repeater ID="someRepeater" runat="server">
<ItemTemplate>
<p>TEST<%# Container.DataItem("NodeAlias")%></p></br>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
First repeater is bound on PageLoad, and second repeater is bound on 1st repeater's item data bound event. However, it seems like my ItemDataBound event is not called, as 2nd repeater items are not being displayed.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim datasetFolders As New DataSet()
Dim da As SqlDataAdapter = New SqlDataAdapter()
Dim sqlQry As String
Dim conn As New SqlConnection(CMS.DataEngine.SqlHelper.ConnectionString)
sqlQry = "SELECT * FROM dbo.CMS_Document WHERE DocumentNamePath LIKE '/Galerie/%' AND DocumentExtensions IS NULL"
da.SelectCommand = New SqlCommand(sqlQry, conn)
conn.Open()
da.Fill(datasetFolders)
conn.Close()
FolderRepeater.Dispose()
FolderRepeater.DataSource = datasetFolders
FolderRepeater.DataBind()
End Sub
and this would be the itemDataBound event. Text in response.write("test") is not displayed on my webpage, so I suspect its never called?
Protected Sub CategoryRepeater_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles FolderRepeater.ItemDataBound
Response.Write("test")
Dim item As RepeaterItem
item = e.Item
Dim imageFolder As New DataSet
Dim da As SqlDataAdapter = New SqlDataAdapter()
Dim sqlQry As String
Dim conn As New SqlConnection(CMS.DataEngine.SqlHelper.ConnectionString)
sqlQry = "SELECT * FROM dbo.View_CONTENT_File_Joined WHERE NodeAliasPath LIKE '/Galerie/" & e.Item.DataItem("DocumentName") & "/%'"
da.SelectCommand = New SqlCommand(sqlQry, conn)
conn.Open()
da.Fill(imageFolder)
conn.Close()
Dim someRepeater As Repeater
someRepeater = e.Item.FindControl("someRepeater")
someRepeater.DataSource = imageFolder
someRepeater.DataBind()
End Sub

Problem was with this:
FolderRepeater.Dispose()
It seems like dispose disables future events? Anyway, now that I commented it out it works.

It's good that you already found the problem here:
FolderRepeater.Dispose()
FolderRepeater.DataSource = datasetFolders
FolderRepeater.DataBind()
If this was not a typing mistake, you should really read up on the proper use of the Dispose() function. There is plenty of information about this when you search the web, ie.:
When and How to Use Dispose and Finalize
When, How, Where and Why to use Dispose

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:

Program won't give me the right Sum

I want to get the sum of the selected items in the listbox and display them in a label but i am always getting 0,i also want to put the selected items in another label too which is also not working.
Here is what the code look like:
Dim sum As Integer
Dim Items1 As String = "None"
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Label2.Text = Request.QueryString("Name").ToString()
Dim connetionString As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim sql As String
connetionString = "Data Source=.;Initial Catalog=Shop;integrated security=true"
sql = "select PhoneName,PhonePrice from SmartPhones"
connection = New SqlConnection(connetionString)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ListBox1.DataSource = ds.Tables(0)
ListBox1.DataTextField = "PhoneName"
ListBox1.DataValueField = "PhonePrice"
ListBox1.DataBind()
End Sub
code where the display should happen:
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles TotalPrice.Click
sum = 0 'reset sum to 0
For Each i As Integer In ListBox1.GetSelectedIndices
Dim CurrentItem As ListItem = ListBox1.Items(i)
sum = sum + CInt(CurrentItem.Value)
Items1 = Items1 + " , " + CStr(CurrentItem.Text)
Next
Label3.Text = Items1
Label1.Text = sum
End Sub
Here is the page Design and the Page On the web Respectively:
PhoneName is of type varchar in database & PhonePrice is of type integer (Both Filled correctly).
ListBox code:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" ></asp:ListBox>
What's the reason that the code won't give me the desired result?
What is happening is that when you click TotalPrice a postback is performed (What is a postback?). If you look at the ASP.NET page lifecycle you will see that the Load event happens before the postback event handling (e.g. your Sub Button2_Click).
So, you click the button, it runs the Me.Load handler and... your list is reset before the click handler gets a chance to run.
There is a property you can check to see if the page is running as a result of a postback: Page.IsPostBack.
So all you need to do is check it to see if you need to populate the list:
Sub FillItemsList()
Dim connectionString As String = "Data Source=.;Initial Catalog=Shop;integrated security=true"
Dim dt As New DataTable()
Using connection As New SqlConnection(connectionString)
Dim sql As String = "SELECT PhoneName,PhonePrice FROM SmartPhones"
Using adapter As New SqlDataAdapter(sql, connection)
adapter.Fill(dt)
End Using
End Using
ListBox1.DataSource = dt
ListBox1.DataTextField = "PhoneName"
ListBox1.DataValueField = "PhonePrice"
ListBox1.DataBind()
End Sub
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Label2.Text = Request.QueryString("Name").ToString()
If Not Page.IsPostBack Then
FillItemsList()
End If
End Sub

Programmatically sort GridView

I am using a GridView in ASP.NET and am building it up programmatically. However, when I go to sort, I am getting an error thrown because the event is not being handled correctly.
I've not worked with ASP.NET GridViews in a long time and am extremely rusty on this one.
This is the code I have so far:
Public Sub GetData()
Using sqlConn As New SqlConnection(_connstr)
Dim sqlcmd As New SqlCommand()
sqlcmd.Connection = sqlConn
sqlcmd.CommandType = CommandType.StoredProcedure
sqlcmd.CommandText = "dbo.uspGetEmailAudit"
sqlcmd.Parameters.Add(requestIdParam)
Using sqlda As New SqlDataAdapter(sqlcmd)
sqlda.Fill(_dt)
End Using
End Using
BindData(_dt)
End Sub
Private Sub BindData(dt As DataTable)
GridView1.DataSource = _dt
GridView1.AllowSorting = True
GridView1.AllowPaging = True
GridView1.PageSize = 15
GridView1.DataBind()
End Sub
Protected Sub sorting(sender As Object, e As GridViewSortEventArgs)
ViewState("sortexp") = e.SortExpression
GridView1.DataSource = GetData()
GridView1.DataBind()
End Sub
The error that I am getting is:
The GridView 'GridView1' fired event Sorting which wasn't handled.
Somewhere in Form_Load or otherwise, you need to wire up the OnSorting event.
Examples are here:
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting(v=vs.110).aspx
In your GridView markup, tell it to use your sub:
<asp:GridView runat="server" OnSorting="sorting" id="GridView1" />
You have to wire it up, it won't do it for you.
If you create the GridView in code, you'll need to do the VB.NET equivalent of this C# code (sorry, I'm not a VB guy)
GridView1.OnSorting += sorted;

asp.net update database from drop down list

I'm trying to allow a user select their marital status that will update a field in a database. This is fine when it is the user's first time, but if they want to update it again, it will not update.
If I choose a data source, if they wish to update, they aren't given any other options in the DDL other that what was selected the first time.
*ASPX*
<asp:DropDownList ID="DDLMarital" runat="server" TabIndex="1">
<asp:ListItem Value = "Single" Text = "Single">Single</asp:ListItem>
<asp:ListItem Value = "Married" Text = "Married">Married</asp:ListItem>
<asp:ListItem Value = "Separated" Text = "Separated">Separated</asp:ListItem>
<asp:ListItem Value = "Divorced" Text = "Divorced">Divorced</asp:ListItem>
</asp:DropDownList>
****ASPX.VB*****
'binding...
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim dvSql4 As DataView =
DirectCast(SqlMarital.Select(DataSourceSelectArguments.Empty), DataView)
For Each drvSql4 As DataRowView In dvSql4
DDLMarital.Text = drvSql4("Marital_Status").ToString()
Next
End Sub
'updating the database when the "Next" button is clicked
Protected Sub BtnNext_Click(sender As Object, e As System.EventArgs) Handles BtnNext.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\scrummingit2.mdf;Integrated Security=True;User Instance=True"
con.Open()
cmd.Connection = con
cmd.CommandText = ("UPDATE Student_Personal_Details SET Marital_Status = #Marital WHERE Student_No = #StudentNo")
Dim maritalParam As New SqlParameter("#Marital", DDLMarital.Text)
Dim studentNoParam As New SqlParameter("#StudentNo", lblEnrolmentStudentNumber.Text)
lblEnrolmentStudentNumber.Text = Session("Student")
cmd.Parameters.Add(maritalParam)
cmd.Parameters.Add(studentNoParam)
cmd.ExecuteNonQuery()
con.Close()
End Sub
Can anyone help? Getting desperate now after days of not finding any answers on Google.
You should check for a PostBack, and assign the selected value only if it is not a PostBack.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack
Dim dvSql4 As DataView =
DirectCast(SqlMarital.Select(DataSourceSelectArguments.Empty), DataView)
For Each drvSql4 As DataRowView In dvSql4
DDLMarital.Text = drvSql4("Marital_Status").ToString()
Next
End If
End Sub
The user's selection is at present being ignored as the value get reset on every Load

ASP.Net: need help with dropdown list bound to a database column

I have created database which has columns
- MemName
- monthlyAmt
- CurrentInstAmt
I have bound the Memname column with a DropDownList box;
onselection of memname value in DropDownList box, the corresponding values of currentInstAmt and monthlyamt should be displayed in Textbox.
I am beginer in asp.net
code -
DataSet dsMemname = new DataSet();
try
{
con.ConnectionString = strcon;
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_Memcollection";
SqlDataAdapter adp = new SqlDataAdapter(cmd.CommandText, con);
adp.Fill(dsMemname);
ddlmemname.DataTextField = "MemName";
ddlmemname.DataSource = dsMemname;
ddlmemname.DataBind();
}
catch (Exception ex)
{
throw ex;
}
EDIT:
First, set your dropdownlist's DataValueField, just like the DataTextField: as so:
ddlmemname.DataValueField = "MemName";
END EDIT
Set your dropdownlist's autopostback="True" as so:
<asp:dropdownlist id="DropDownList1" runat="server" autopostback="true">
</asp:dropdownlist>
and then in the code behind for your page, add an event for your drop down as so:
Protected Sub DropDownList1_SelectedIndexChanged _
(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles DropDownList1.SelectedIndexChanged
Dim selval As String = DropDownList1.SelectedValue
TextBox1.Text = getMonthlyAmt(selval)
TextBox2.Text = getCurrentAmt(selval)
End Sub
The two get() methods are your own code to look up your relevant values. Also, you may want to optimize them to one call in some manner depending on where you're pulling them from and performance considerations.

Resources