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:
Related
I am asking a question about Ajax File Upload again.. T_T
I have an ASP.NET webform (using VB.NET) which is using Ajax File Upload. I update my database table whenever I upload a file. I am checking a file is already uploaded or not when I drag into my upload panel and click the upload button.
If the target file is already uploaded, I want to show my error label like 'the file is already uploaded' . But the label doesn't showing . I did debug to trace the result and the file is really existing and it went through my label text setting but didn't show on my form.
Which part of my code is being wrong? I hope someone can guide me.
here is my asp code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
//customize the drag panel
function AjaxFileUpload_change_text() {
Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "Click Upload";
document.getElementsByClassName('ajax__fileupload_uploadbutton')[0].style.width = '100px';
}
</script>
<div style="width:40%;padding:25px;margin-left:200px">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" AllowedFileTypes="pdf" MaximumNumberOfFiles="10" />
<asp:Button ID="cmdDone" runat="server" Text="Done" style="display:none" ClientIDMode="Static" />
<script>
function MyCompleteAll() {
$('cmdDone').click()
}
</script>
</div>
<asp:Label ID="lblmsg" runat="server" Text="" Width ="150px" style="color:red"></asp:Label><br />
</asp:Content>
.vb code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "AjaxFileUpload_change_text();", True) //customize ajax panel
lblmsg.Text = "" //error display
End Sub
Protected Sub MyCompleteAll(sender As Object, e As AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim filename As String = e.FileName.Split(".").First + "_" + fileupload + ".pdf"
Dim path As String = Server.MapPath("~/uploads/")
//to add a database table of files up-loaded.
Dim constr As String = CONN + g_schema
Using con As New MySqlConnection(constr)
con.Open()
'check file is already uploaded
Dim select_seq As String = "select fname from filetable where fname like '" +
e.FileName.Split(".").First + "%'"
Dim cmd As New MySqlCommand(select_seq, con)
Dim reader = cmd.ExecuteReader()
While reader.Read()
fname = reader(0).ToString
End While
con.Close()
//the file is already uploaded
If fname IsNot "" Then
lblmsg.Text = "Already uploaded. Please upload the other files."
Else
// Upload process code
End Sub
Thank you.
I going to suggest you check the file on the file upload done event.
So, we can THEN build up a list of files that exist - you have the possibility of more then one file up-load.
So, I suggest dropping in a text box to "hold" each bad (duplicate) file.
So, lets persist into session() the duplicate files (we can NOT use controls on the page in the 3 events (start, complete, complete all).
So, we have this code:
Dim DupList As New List(Of String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("DupList") = DupList
txtDups.Visible = False
Else
DupList = Session("DupList")
End If
End Sub
And say this markup - the text box, a grid view, and of course the FileUpload.
So, say this markup up:
<div style="width:40%;padding:25px">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384"
/>
<asp:Button ID="cmdDone" runat="server" Text="Done"
style="display:none" ClientIDMode="Static"/>
<asp:TextBox ID="txtDups" runat="server" TextMode="MultiLine" Width="523px"></asp:TextBox>
<script>
function MyCompleteAll() {
$('#cmdDone').click()
}
</script>
<asp:GridView ID="Gfiles" runat="server" CssClass="table" DataKeyNames="ID"></asp:GridView>
</div>
So far - VERY good you have that JavaScript button click to get our VERY imporant and needed final post back when done.
So, a single file upload done event - looks like this:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
' now code to add say to a database table of files up-loaded.
' but FIRST CHECK if the file already exists
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = #F"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it
Dim strFileSave As String
strFileSave = Server.MapPath("~/Content/" & e.FileName)
AjaxFileUpload1.SaveAs(strFileSave)
' now add to database
Dim NewRow As DataRow = rstFiles.NewRow
NewRow("FileName") = e.FileName
NewRow("UpLoadTime") = Date.Now
NewRow("User_id") = 1
NewRow("Size") = e.FileSize
NewRow("SavePath") = Path.GetDirectoryName(strFileSave) ' get path only
rstFiles.Rows.Add(NewRow)
MyRstUpdate(rstFiles, "MyUpLoadFiles")
End If
End Sub
So note in above HOW WE SKIP the file if it exists. And of course if it does exist, then we of course don't make an entry in the MyFilesUpLoad table.
Ok, so all files up-load - that js button click fires, and we now have this final code stub run:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
' this final code is triggered by the javascrpt "click" on
' all file uplaod done
' if there are some duplicates - dispay to user.
If DupList.Count > 0 Then
txtDups.Visible = True
For Each s As String In DupList
If txtDups.Text <> "" Then txtDups.Text &= vbCrLf
txtDups.Text &= s & " already exists - skipped and not uploaded"
Next
End If
' now addtonal code - maybe display gird of up-loaded files
Dim strSQL As String = "select * from MyUpLoadFiles where UpLoadTime >= #D"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#D", SqlDbType.DateTime).Value = Date.Today
Gfiles.DataSource = MyRstP(cmdSQL)
Gfiles.DataBind()
' hide up-loader
AjaxFileUpload1.Visible = False
End Sub
So, it will look like this:
We hit ok, and now we have/see this:
Ok, so now lets try to re-upload two files that exist.
We So, we will see this:
So, we persist that "bad" list, and skip/don't save the file in the complete event.
And here are the two data helper routines - I don't think it needs much suggesting that one gets VERY tired VERY fast by having to type over and over some simple code to get data into a table - so I used these two helper routines to save World poverty and a few keyboards
Public Function MyRstP(cmdSQL As SqlCommand) As DataTable
Dim rstData As New DataTable
Using cmdSQL
Using conn = New SqlConnection(My.Settings.TEST4)
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Public Sub MyRstUpdate(rst As DataTable, strTable As String)
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT * from " & strTable, conn)
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
conn.Open()
da.Update(rst)
End Using
End Using
End Sub
Edit: Check for "confirmed" file
Follow up question was not only does the file exist, but at some point (or some how - not yet disclosed), the use has the means to check box, or change the status of the up-loaded files. And if file has not yet been confirmed, then we still allow up-loading.
So, the code in question would be this:
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = #F
AND Confirmed = 9"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists.
' file is confirmed - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it - (or not confirmed)
I'm trying to Filter GridView with Multiple 'DropDownList with Multi-Select' using jQuery Select2.
I'm following the codes from this link >> https://www.aspsnippets.com/questions/182622/Filter-GridView-with-multi-select-DropDownList-using-jQuery-Select2-Plugin-in-ASPNet-using-C-and-VBNet/ this can only filter gridview using one dropdown. My requirement is to filter gridview using two dropdowns with Multi-Select.
I'm getting stuck at 'condition1' and 'where' condition in the below code
Any help or lead to fix the below code is highly appreciated.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlCountries.DataBind()
End If
End Sub
Protected Sub OnSearch(ByVal sender As Object, ByVal e As EventArgs)
Dim query As String = " SELECT distinct([CUSTOMER_NAME_CMT]),[Acc Number] FROM dbo.MASTERDATA_PRO"
Dim condition As String = String.Empty
For Each item As String In hfSelected.Value.Split(","c)
condition += String.Format("'{0}',", item)
Next
Dim condition1 As String = String.Empty
For Each item As String In hfSelected_ACCNO.Value.Split(","c)
condition1 += String.Format("'{0}',", item)
Next
If Not String.IsNullOrEmpty(condition) Then
condition = String.Format(" WHERE CUSTOMER_NAME_CMT IN ({0}) ", condition.Substring(0, condition.Length - 1))
End If
If Not String.IsNullOrEmpty(condition1) Then
condition1 = String.Format(" and [Acc Number] IN ({0}) ", condition1.Substring(0, condition1.Length - 1))
End If
GridView1.DataSource = GetData(query & condition & condition1 )
GridView1.DataBind()
End Sub
Private Function GetData(ByVal query As String) As DataTable
Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(query)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
cmd.Connection = con
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Using
End Function
End Class
Ok, unfortantly that example is a mess - and does not work correctly.
And it has extras things like that hidden field in the markup that's not even used.
However, there are "several issues that crop up"
First up?
Unfortantly the asp.net "dropdown" list control does not work if you want multi-select to work.
However, have no fear - just use the standard "HTML" "select" tag.
And MORE interesting, is that the select tag quite much supports darn near everything the DropDownList supports (they are actually much the same - the asp.net is based on it. In fact ALL of the settings are much the same, and you can even use data bound.
(for most dropdowns - yes, I recommend you continue to use dropDownList).
however, that "select2" jQuery add-in? It has issues.
So, here is working example. (we will select some Cities, and display hotels).
So, our markup looks like this:
<asp:Label ID="Label1" runat="server" Text="Select City(s) for Hotels" Style="float:left;margin-right:25px" Font-Size="Large"></asp:Label>
<select ID="cboCity" runat="server" Style="width:200px"
DataTextField="City"
DataValueField="City"
CssClass="form-control"
ClientIDMode="Static">
</select>
<asp:Button ID="Button1" runat="server" Text="Search" style="margin-left:25px"/>
</div>
<br />
<br />
<div style="clear:both;float:left;width:60%">
<asp:GridView ID="GridView1" runat="server" class="table table-hover" ></asp:GridView>
</div>
</form>
<script>
$(document).ready(function () {
$("#cboCity").select2({
placeholder: 'Select city(s)',
allowClear: true
});
});
</script>
our code behind can look like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' load our combo
Using cmdSQL As New SqlCommand("SELECT City from City ORDER BY City",
New SqlConnection(My.Settings.TEST4))
cmdSQL.Connection.Open()
cboCity.DataSource = cmdSQL.ExecuteReader
cboCity.DataBind()
cboCity.Multiple = True
End Using
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using cmdSQL As New SqlCommand("SELECT * FROM VHotels ",
New SqlConnection(My.Settings.TEST4))
Dim strWhere = ""
For Each MySelect As ListItem In cboCity.Items
If MySelect.Selected Then
With cmdSQL.Parameters
If strWhere <> "" Then strWhere &= ","
strWhere &= "#" & .Count
.Add("#" & .Count, SqlDbType.NVarChar).Value = MySelect.Value
End With
End If
Next
cmdSQL.Connection.Open()
cmdSQL.CommandText &= "WHERE City in (" & strWhere & ") ORDER BY HotelName"
GridView1.DataSource = cmdSQL.ExecuteReader
GridView1.DataBind()
End Using
End Sub
The results look like this:
Note carefull how we had to remove the select=multiple from the markup - it does not work if you do that - but in the page load when we load up the combo box, note the code setting cboCity.Multiple = True.
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
I developed the following code for editing a GridView (following a tutorial written in C#), It goes into edit mode, but my edits do not take effect, here is my code:
aspx.vb code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Globalization
Partial Class MemberPages_editOutage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim dt As New DataTable()
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Try
connection.Open()
Dim sqlStatement As String = "SELECT OutageDetailId, LocationName, Description, DetailDescription, CreateDate, StatusId FROM OutageDetail WHERE StatusId='1' ORDER BY CreateDate DESC"
Dim cmd As New SqlCommand(sqlStatement, connection)
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
MyDataGrid.DataSource = dt
MyDataGrid.DataBind()
End If
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Fetch Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
connection.Close()
End Try
End Sub
'edit command
Protected Sub MyDataGrid_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles MyDataGrid.RowEditing
'turn to edit mode
MyDataGrid.EditIndex = e.NewEditIndex
'Rebind the GridView to show the data in edit mode
BindGrid()
End Sub
'cancel command
Protected Sub MyDataGrid_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles MyDataGrid.RowCancelingEdit
' switch back to edit default mode
MyDataGrid.EditIndex = -1
'Rebind the GridView to show the data in edit mode
BindGrid()
End Sub
'Update Function
Private Sub UpdateRecord(ByVal SOutageDetailId As String, ByVal SDescription As String, ByVal SDetailDescription As String, ByVal SCreateDate As String, ByVal SstatusId As String)
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Dim sqlStatement As String = String.Empty
sqlStatement = "UPDATE OutageDetail SET #OutageDetailId = #OutageDetailId, LocationName = #LocationName, " & _
"Description = #Description, DetailDescription= #DetailDescription, " & _
"CreateDate = #CreateDate, StatusId = #StatusId WHERE OutageDetailId = #OutageDetailId"
connection.Open()
Dim cmd As New SqlCommand(sqlStatement, connection)
cmd.Parameters.Add(New SqlParameter("#OutageDetailId", SOutageDetailId))
cmd.Parameters.Add(New SqlParameter("#LocationName", SDescription))
cmd.Parameters.Add(New SqlParameter("#Description", SDescription))
cmd.Parameters.Add(New SqlParameter("#DetailDescription", SDetailDescription))
cmd.Parameters.Add(New SqlParameter("#CreateDate", SCreateDate))
cmd.Parameters.Add(New SqlParameter("#StatusId", SstatusId))
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
' MyDataGrid.EditIndex = -1
connection.Close()
BindGrid()
End Sub
'update command
Protected Sub MyDataGrid_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles MyDataGrid.RowUpdating
'Accessing Edited values from the GridView
Dim SOutageDetailId As String = MyDataGrid.Rows(e.RowIndex).Cells(0).Text
Dim SDescription As String = MyDataGrid.Rows(e.RowIndex).Cells(1).Text
Dim SDetailDescription As String = MyDataGrid.Rows(e.RowIndex).Cells(2).Text
Dim SCreateDate As String = MyDataGrid.Rows(e.RowIndex).Cells(3).Text
Dim SstatusId As String = MyDataGrid.Rows(e.RowIndex).Cells(4).Text
'Call the function to update the GridView
UpdateRecord(SOutageDetailId, SDescription, SDetailDescription, SCreateDate, SstatusId)
MyDataGrid.EditIndex = -1
'Rebind Gridview to reflect changes made
BindGrid()
End Sub
End Class
aspx code:
<asp:GridView id="MyDataGrid" runat="server"
Width="750px"
CssClass="gridViewEdit"
BackColor="White"
BorderColor="Black"
CellPadding="3"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#FFFFFF"
OnEditCommand="MyDataGrid_RowEditing"
OnCancelCommand="MyDataGrid_RowCancelingEdit"
OnUpdateCommand="MyDataGrid_RowUpdating"
DataKeyField="OutageDetailId"
Font-Names="Verdana">
<Columns>
<asp:CommandField ShowEditButton="True" EditText="Edit" CancelText="Cancel" UpdateText="Update" />
</Columns>
<HeaderStyle BackColor="White"></HeaderStyle>
</asp:GridView>
Could someone shed some light on what I am missing please.
The moment you hit the Edit, you go to get the ID of the line that must be update, and you get it from this line
Dim SOutageDetailId As String = MyDataGrid.Rows(e.RowIndex).Cells(0).Text
but on page load you have set
If Not IsPostBack Then
BindGrid()
End If
so on the post back, the grid up to the point you try to get the id from the cell, is empty.
Two ways, ether give again the data on post back, and make DataBind right after the update, or get the Index of the Grid View to make the Update, and not take the Cell.
For example, I will change your code to:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
BindGrid()
End Sub
Private Sub BindGrid()
Dim dt As New DataTable()
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Try
connection.Open()
Dim sqlStatement As String = "SELECT OutageDetailId, LocationName, Description, DetailDescription, CreateDate, StatusId FROM OutageDetail WHERE StatusId='1' ORDER BY CreateDate DESC"
Dim cmd As New SqlCommand(sqlStatement, connection)
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
MyDataGrid.DataSource = dt
If Not IsPostBack Then
MyDataGrid.DataBind()
End If
End If
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Fetch Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
connection.Close()
End Try
End Sub
[*] Assuming that you do not have other bugs on sql...
I'm simply databinding the data (containing date values) I got with a DataReader as in the following code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim id As Integer = Request.QueryString("id")
'Start connection
Dim cs As String = ConfigurationManager.ConnectionStrings("Access 2010").ConnectionString
Dim cn As New OleDbConnection(cs)
cn.Open()
'Retrieve Jobs Data
Dim cmd As New OleDbCommand
With cmd
.Connection = cn
.CommandText = "SELECT Nome, Descricao, Data, Autor FROM Jobs WHERE ID = #ID"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#ID", id)
End With
Dim dbReader As OleDbDataReader = cmd.ExecuteReader()
If Not Page.IsPostBack Then
'Populate Dropdown Jobs
dtlJob.DataSource = dbReader
dtlJob.DataBind()
End If
dbReader.Close()
End Sub
And I'm getting the values like 30/12/1899 00:00:51. I checked my database and the record is correct: it appears 12/10/2011. How do I format the Date field since I just used .DataSource and .DataBind?
Find the details view on the aspx page and you need to add the DataFromatString tag to the bound field. IT will be something like this:
<asp:BoundField DataField="datetimefield" HeaderText="DateTime" DataFormatString="{0:d}" />