post back to the same page not working asp.net - asp.net

in my user.aspx page of any particular users account shows all other user names/images as link inside a datalist alongwith the particular users information who is logged in. now i want that if i click any of the other user links the users information should come on the same user.aspx page. i use this code on page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Session("UserName") Is Nothing Then
Response.Redirect("login.aspx")
Else
If Not (IsPostBack) Then
binddata()
binddata1()
binddata2()
End If
End If
End Sub
Sub binddata()
Dim mycommand As New SqlCommand("SELECT * FROM details where id = #id", con)
mycommand.Parameters.Add("#id", SqlDbType.Int)
mycommand.Parameters("#id").Value = Convert.ToInt32(Request.QueryString("id"))
con.Open()
Data.DataSource = mycommand.ExecuteReader
Data.DataBind()
con.Close()
End Sub
Sub binddata1()
Dim mycommand As New SqlCommand("SELECT * FROM details where id = #id", con)
mycommand.Parameters.Add("#id", SqlDbType.Int)
mycommand.Parameters("#id").Value = Convert.ToInt32(Request.QueryString("id"))
con.Open()
nameimage.DataSource = mycommand.ExecuteReader
nameimage.DataBind()
con.Close()
End Sub
Sub binddata2()
Dim mycommand As New SqlCommand("SELECT * FROM details ", con)
con.Open()
user.DataSource = mycommand.ExecuteReader
user.DataBind()
con.Close()
End Sub
and this script for datalist
<asp:DataList ID="custom" runat="server" DataKeyField="Name" RepeatColumns="1" >
<ItemTemplate>
<div><table>
<tr><asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# GetImageURL(Eval("Pic")) %>' PostBackUrl='<%# Eval("id", "user.aspx?id={0}") %>'/></tr>
<tr><td align="left" valign="top" style="width:90px"><asp:LinkButton ID="name" runat="server" ForeColor="Blue" Text='<%#Container.DataItem("Name")%>'></asp:LinkButton></td></tr>
</table></div></ItemTemplate>
</asp:DataList>
this code is working fine for first check/click. when i click one of the users it load the details of the user . but after that when i click another user it doesnot load the details of that user. i want to show : a user logged in , then there on his page there are list of other users with images. when i click any of them the details of the particular should be load in proper places. help me with this

You are checking for a first page load before perform data binding. Remove this check or check for control name that fire postback before it.

Yuriy's answer should work but another approach is to use CommandArgument instead of PostBackUrl. You will need to setup an event handler for your DataList ItemCommand. The CommandArgument value will be your ID value. Your event handler will take that ID and bind it to your data display.

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:

How to check the file is already uploaded or not by using Ajax File Upload?

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)

How to add a button to select an option on gridview in asp.net

I am creating a website so a user can log in and access their own data (through a session) - So far when they log in and are authenticated they are redirected to the user page and can see their own data (in this case it is patients seeing their medication) - I want to provide a button that corresponds with the medicine and allows the user to select the medication so I can use this in an ordering process (if selected then insert to table) - I am not sure how to do this.
From the database there is a patient table (all tables are all made up dummy data):
A Medicine table:
And a link table that connects a patient to their specific medicines:
This is the code that brings up the table showing a patients own particular medicine on the user page:
user.aspx
<asp:Content ID="Content3" ContentPlaceHolderID="contentbody" runat="Server" Inherits="Pages_user" CodeFile="Pages_user.aspx.vb">
<p>
<span class="auto-style2">Please Select Your Medication
</span>
</p>
<asp:GridView ID="GridView1" runat="server" ></asp:GridView>
</asp:Content>
user.aspx.vb :
Partial Class Pages_user
Inherits System.Web.UI.Page
Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
If Not IsPostBack Then
Dim conn As New System.Data.SqlClient.SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Laura\Final_proj\App_Data\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
Dim cmdstring As String = "SELECT pt.PatientId, pt.ForeName, pt.Username, md.Name, md.Purpose, md.Instrcutions " +
"FROM Patient pt INNER JOIN prescription pr ON pt.PatientId = pr.PatientId " +
"INNER JOIN medicine md ON md.MedicineId = pr.MedicineId Where pt.PatientId = #PatientId"
Dim dt As New System.Data.DataTable()
Dim da As New System.Data.SqlClient.SqlDataAdapter(cmdstring, conn)
da.SelectCommand.Parameters.Add("#PatientId", System.Data.SqlDbType.Int).Value = CInt(Session("PatientId").ToString())
conn.Open()
da.Fill(dt)
conn.Close()
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
this is what appears when the user logs in (and ive drawn on what I want to display also):
I hope someone can help been stuck on this for a wile.
Add the following to you grid, like so:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:CommandField ShowSelectButton="True" />
</Columns>
</asp:GridView>
By default clicking this field will cause its corresponding row to be selected. You can then add a datakey that will tell the id or name or whatever of the selected item.
Edit the grid columns and add a select command field, or you can add a button field and interpret the click event.

How to delete a record using LinkButton and refresh the table?

I have an HTML table to display a set of records from database after user entered a patient code or during Page Load when the patient code is passed through Querystring. Each data row has a Delete link button which is created dynamically.
I'd like to have the table refreshed after deletion. However, whenever the link button is clicked, it will postback and all the records will be wiped out unless I reload the data. If I reload the data again after deletion, there will be 2 times data fetching and the table rows will be doubled.
The first 2 rows of the tables are defined on the ASPX for easier styling purpose. If I cleared the table when fetching the data, the first rows will be wiped out as well. I have another 8 tables on different pages created in the same manner, hence I'd rather find other solution rather than defining and styling the rows from code behind.
Any help will be greatly appreciated.
The codes I use are as follow:
ASPX
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblPatientCode" runat="server" Text="Patient Code : "></asp:Label>
<asp:TextBox ID="txtPatientCode" runat="server"></asp:TextBox>
<asp:Button ID="btnFind" runat="server" name="Date" Text="Find" Width="90" CssClass="ButtonNormal" />
<br /><br />
<table id="tblDoctorInformation" class="PatientDetailsTable" runat="server">
<tr><td colspan="2">DOCTOR INFORMATION</td></tr>
<tr>
<td>Doctor In Charge</td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
Code Behind:
Protected PM As New PatientManagement.Common
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GetPatient()
Else
If txtPatientCode.Text <> "" Then
GetPatient()
End If
End If
End Sub
Private Sub GetPatient()
Dim sPatientCode As String = ""
If IsPostBack Then
sPatientCode = Trim(txtPatientCode.Text)
Else
sPatientCode = Trim(Page.Request.QueryString("PatientCode"))
End If
If sPatientCode <> "" Then
Dim dr As SqlDataReader
dr = PM.ExecuteReader("SELECT LOGID,DOCTORNAME FROM PMV_DOCTORINCHARGE WHERE PATIENTCODE='" & sPatientCode & "'")
If dr.HasRows Then
Do While dr.Read
Dim tRow As New HtmlTableRow
Dim tCellDoctorName As New HtmlTableCell
Dim tCellModifyLink As New HtmlTableCell
Dim lb As New LinkButton
'Doctor Name
tCellDoctorName.InnerHtml = PM.GetString_TableCell(dr("DoctorName"))
tRow.Cells.Add(tCellDoctorName)
'Delete links
lb.Text = "Delete"
lb.Attributes.Add("AutoPostBack", False)
lb.CommandArgument = dr("LogID").ToString()
AddHandler lb.Click, AddressOf DeleteRecord
tCellModifyLink.Controls.Add(lb)
tCellModifyLink.Align = "Center"
tRow.Cells.Add(tCellModifyLink)
tblDoctorInformation.Rows.Add(tRow)
Loop
End If
End If
End Sub
Private Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
GetPatient()
End Sub
Protected Sub DeleteRecord(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lbNew As New LinkButton
Dim sResult As String = ""
Dim bResult As Boolean
lbNew = sender
bResult = PM.DeleteMultiRecord(lbNew.CommandArgument, lbNew.CommandName, Session.Item("UserID"), sResult)
If Not bResult Then
MsgBox(sResult, MsgBoxStyle.OkOnly, "Deletion was not successful")
Else
GetPatient()
End If
End Sub
Before Deleting a record, try to place a PatientID in Textbox and Delete the record, then Table will Display the records matching with the TextBox input.
The Problem is with PageLoad() method, if the TextBox is Empty And It is a Postback, then GetPatient() method will not be called. So try to modify the PageLoad() Method.
Better to remove IsPostBack condition in PageLoad().
I have searched around and it seems dynamic handler is best to be declared during PageInit. For my case, as the link button control needs to carry some values on the respective data row, it seems I can't avoid calling GetPatient to create controls.
To move on with the issue, I did a workaround by using Javascript. I created a hidLogID hidden field on ASPX page. I changed the link button to an <a> control and call a javascript function passing the dr("LogID"). The javascript function will assign the value to hidLogID and submit the page. PageLoad will call DeleteRecord()when hidLogID value is not blank. The value for hidLogID will be cleared on DeleteRecord().
Thank you for all the help!

set label value in vb.net

I'm usually a PHP guy but got stuck doing a project in vb.net.
I have a query (sqldatasource) that returns a single value (the last update date).
I want to use a label to say something like "Last updated: " < Label = (returned value) >
In PHP this would be simple. In vb.net, all I can find are endless badly written code behinds showing how you'd execute the query onLoad then bind it to the label.
Is this really the only way to do this? It seems like a ridiculously simple problem to have such a long solution. I have used a datagrid control to just bind the query result directly, but it prints the column name as well as the date, so it's not ideal.
Any ideas?
In your Page_Load method, run your query. On your page.aspx, you have a form control, lets call it label1. Set label1.text = queryResult.
Sub Page_Load()
dim myConnection as new data.sqlclient.sqlconnection
dim myCommand as new data.sqlclient.sqlcommand
dim sqlReader as data.sqlclient.sqldatareader
myConnection.connectionString = 'enter your connection string details'
myConnection.Open()
myCommand = New SqlCommand("Select lastUpdated from yourTable", myConnection)
sqlReader = myCommand.ExecuteReader()
if sqlReader.hasRows then
sqlReader.read()
label1.text = Format("MM/dd/yyyy", sqlReader("lastUpdated"))
end if
End Sub
And your page.aspx (somewhere)
<asp:label id="Label1" runat="server" />
PS - I may be off on the format function above, been awhile.
EDIT based on user comment:
Well, for what you are doing, I wouldn't really recommend a SQLDataSource as it is really meant to be bound to a control such as a gridview or repeater. However, if you want to use the SQLDataSource, you will need to bind to a DataView in your code-behind. From there, you can access each row (you should only have one) and column by name.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dv As New Data.DataView
'use the id of your SqlDataSource below'
dv = SqlDataSource1.Select(DataSourceSelectArguments.Empty)
Label1.Text = dv.Table.Rows(0)("LastUpdated")
End Sub
TO use a connection string from the web.config:
Web.Config File:
<appSettings>
<add key="strConnectionString" value="Data Source=192.168.0.55;Database=Times;User ID=sa;PassWord=sa"/>
</appSettings>
Code Behind:
Dim sqlConn as new data.sqlClient.SqlConnection()
sqlConn.ConnectionString=ConfigurationManager.ConnectionStrings("strConnectionString").ConnectionString
sqlConn.Open()

Resources