DIsplay real time SQL data on web form - html

I am working on a small project but currently stuck in the process and your help would be much appreciated.
I am trying to display data from one of my SQL tables onto web form (asp), which will effectively be updating as long as data is being entered into the table.
I have managed to get it to work by using the META Tag which refreshes the page every 2 seconds, but I know this is not an ideal way of doing it. It was advised to me to update the web form only from server to client when there is a new inserted value, however I do not know how to approach this.
Please see below to my current code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = "Cache Refresh:" & _
Date.Now.ToLongTimeString
SqlDependency.Start(GetConnectionSTring())
Using connection As New SqlConnection(GetConnectionSTring())
Using Command As New SqlCommand(GetSQL(), connection)
Dim Dependency As New SqlCacheDependency(Command)
Dim NumberOfMinutes As Integer = 3
Dim Expires As Date = _
DateTime.Now.AddMinutes(NumberOfMinutes)
Response.Cache.SetExpires(Expires)
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(True)
Response.AddCacheDependency(Dependency)
connection.Open()
GridView1.DataSource = Command.ExecuteReader()
GridView1.DataBind()
End Using
End Using
End Sub
Private Function GetConnectionSTring() As String
Return "Data Source=xxxxxxxxx; Initial Catalog=Test; User ID=xxx; Password= xxx;"
End Function
Private Function GetSQL() As String
Return "SELECT ProductCode, ProductName, Cost FROM dbo.OrderTempTable"
End Function
Thank you for your input.

I think you have to check the DB every certain time.
THIS is for PHP but the idea is the same.
HERE another example.

Related

How can I get the usernames in the account?

I'm making a VB.Net application which connects to a MySql database.
My application has many Accounts, and each account has several Users. I want to show this information, but the application just shows the first user of each account.
This is the code:
Public Function id(Label2 As String) As Double
Using connection = Getconnection()
connection.Open()
Using commandid = New MySqlCommand
commandid.Connection = connection
commandid.CommandText = "SELECT *FROM player.player
Where player.account_id=" & testString & V
Dim read = commandid.ExecuteReader
If read.HasRows Then
While read.Read
ActivateUser.namecharacter = read.GetString(2)
ActivateUser.job = read.GetString(3)
End While
read.Dispose()
Return True
Else
MessageBox.Show(" no ")
Return False
End If
connection.Close()
connection.Dispose()
End Using
End Using
End Function
How can I fix this to show all the users in the account?
Just create you connection in the method where you use it. Get rid of GetConnection just use a class level variable for the connection string.
Don't open a connection until directly before you use it.
You can include the command in the same using block by adding a comma at the end of the first line. Commands also need to be disposed. The command constructor can take the CommandText and the Connection as parameters.
What datatype is account_id in the database? I am going to guess it is a string type. Is V a variable or is it meant to be the string "V"? I am going to guess a hardcoded string. Where does testString come from? I am going to guess Label2 (terrible non-descriptive name) is teststring.
Never concatenate strings for you sql. Always use parameters.
A reader also needs to be closed and disposed so use Using blocks. The whole idea of accessing the database is to get in and out as quickly as possible. Don't set properties of ActivateUser and never show a message box. The user could have gone to lunch and your connection is left flapping in the breeze.
You have the datatype of your function as Double but your return statements have Booleans. Won't work.
It is not necessary to close and dispose the connection. The End Using does that.
Private ConStr As String = "Your connection string"
Public Function id(Label2 As String) As DataTable
Dim dt As New DataTable
Using connection As New MySqlConnection(ConStr),
commandid As New MySqlCommand("SELECT *FROM player Where account_id= #TestString;", connection)
commandid.Parameters.Add("#TestString", MySqlDbType.VarChar).Value = Label2 & "V"
connection.Open()
Using reader = commandid.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Then back in the User Interface code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = id(Label2.Text)
If dt.Rows.Count > 0 Then
ActivateUser.namecharacter = dt(0)(2).ToString
ActivateUser.job = dt(0)(3).ToString
Else
MessageBox.Show(" no ")
End If
End Sub
This makes a good separation of from your database code.

Copy GridView data to table in database

I have data in a GridView and I need to copy it to a table in a database.
Let's say my first GridView is GridView1; GridView1's database source is subjects_enrolled. After I'm done using GridView1 it's data needs to clear and in addition, clear the data in the source table.
Note: The primary purpose of GridView1 is for displaying data for printing a page, but I want to save or transfer all data in GridView1 to a database table before losing the GridView1 data.
Here is my code so far:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("mcbdatabseConnectionString").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT Subject_ID, Subject, Units FROM mcbdatabse.subject_enrolled")
Using sda As New MySqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End If
txtDate.Text = Date.Today.ToString("yyyy-MM-dd")
End Sub
When you doing some unnormal activity about databases you can be sure that you are in a bad plan. So in your case i can not understand why you want to do this.
You have better ways to do this, you can put all data in one table and add a column named 'enrolld' to filter data as you want and on user click you can delete or enrol the record.
But if you want to continue this way, you we have some events in gridview that can help:
RowDeleting, RowUpdating
If a row affected the related event fires and you can get the id of the record:
protected sub GridView1_RowDeleting(byval sender as object, byval e as GridViewDeleteEventArgs)
{
dim a as object = e.Keys["Id"]
'or
dim a as object = e.Keys[0]
}
To access the id of your record and do what you want with this.

How do I loop Through Each Records in SQL server with Time Gap

I am making a CMS portal for my company which will fetch records from SQL server using ASP.NET:
My problem is that when I fetch values it only shows the last one. But my need is that it should display one by one values with say 5-10 seconds gap in between here is my code:
Imports System
Imports System.Data.Sql
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Dim connectionString As String = "Data Source=soemserv;Initial Catalog=data;User Id=master; Password=hushotn;"
Dim conn As New SqlConnection(connectionString)
Public Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
conn.Open()
Dim comm As New SqlCommand("select Queue,[Timing(IST)],[Status at],TAT,[Staffing at] from DTD_LCD_Queue_Status", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
While reader.Read()
lblQueueName.Text = reader("Queue").ToString.Trim
lblTimingIST.Text = reader("Timing(IST)").ToString.Trim
lblStatusAt.Text = reader("Status at").ToString.Trim
lblTAT.Text = reader("TAT").ToString.Trim
lblStaffingAt.Text = reader("Staffing at").ToString.Trim
End While
End Sub
End Class
How do I loop though each record I tried Do and Loop but its not working...
Thanks in advance!
EDIT
One Step Ahead with no LUCK!!!!
I have written this code but still getting the last row only
For I As Integer = 0 To 15
lblTemp.Text = I.ToString
Dim comm As New SqlCommand("select Queue,[Timing(IST)],[Status at],TAT,[Staffing at] from DTD_LCD_Queue_Status where SrNo='" + lblTemp.Text + "';", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
While reader.Read()
lblQueueName.Text = reader("Queue").ToString.Trim
lblTimingIST.Text = reader("Timing(IST)").ToString.Trim
lblStatusAt.Text = reader("Status at").ToString.Trim
lblTAT.Text = reader("TAT").ToString.Trim
lblStaffingAt.Text = reader("Staffing at").ToString.Trim
Thread.Sleep(2000)
End While
Next
Note I have dynamically given rows i.e 0 to 15
Please guide me!!
Only the last values are printed because : you are fetching a group of rows(data) through the readr and in first iteration of the while loop the first rows(data) are copied to the controls then for the second iteration the contents in the controls are over written with the second row. This will happens in each iteration hence only the last data are displayed.
- This can be avoided by using
Group of controls which are dynamically created(but not practical and good)
using DataGridView(grid) to display the items How to do this
**The method you ware suggested (using Timer) is also possible but it is not a good programming practice only the last values ware displayed all the others flashed for a duration of 5-10 seconds **

Populate a textbox with mysql data after a combobox selection

So I have 2 mysql tables, one called "Service_Details" and one called "Payment_details"
I have a combobox in my form which displays the "service_id" field from the service table.
I'm trying to code a textbox, so when I select the service id from the combobox it writes the "service" which is another field in my service details table. The service id is linked to a service.
I am getting errors 'identifier expected' at [0] and 'Value of type 'system.data.datatablecollection' cannot be converted to 'string' at dss.tables
I can't seem to get it working after browsing the internet for an hour
Here is my code:
Private Sub cbxserviceid_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxserviceid.SelectedIndexChanged
Dim dss As New DataSet
Dim daa As New MySqlDataAdapter("SELECT * from service_details WHERE ServiceID='" + cbxserviceid.Text + "'", objconnection)
Dim cmddd = New MySqlCommandBuilder(daa)
daa.Fill(dss)
txtService1.Text = dss.Tables[0].Rows[0]["Service"].ToString();
End Sub
The indexes in VB.NET are expressed using the round braces, the square brackets are used in C#
txtService1.Text = dss.Tables(0).Rows(0)("Service").ToString()
Also avoid to use string concatenation for sql command texts, use always a parameterized query
Private Sub cbxserviceid_SelectedIndexChanged(......)
Dim dss As New DataSet
if cbxserviceid.SelectedIndex <> -1 Then
Dim daa As New MySqlDataAdapter("SELECT * from service_details WHERE ServiceID=#id", _
objconnection)
daa.SelectCommand.Parameters.AddWithValue("#id", Convert.ToInt32(cbxserviceid.Text))
daa.Fill(dss)
txtService1.Text = dss.Tables(0).Rows(0)("Service").ToString()
End If
End Sub
I have also removed the creation of the MySqlCommandBuilder, being the adapter a local variable it has no sense or effect (if this is all your code in this event of course).
Looking at the comments below and the chat with the poster there is also another error to fix.
When assign a DataSource, DisplayMember and ValueMember property of a combobox it is mandatory to follow a precise order to avoid unwanted side effects
cbxserviceid.DisplayMember = "ServiceID"
cbxserviceid.ValueMember = "ServiceID"
cbxserviceid.DataSource = datatable

remove redundant columns in selectable query datagridview

I have a single Datagridview on one of my windows forms that I intend to have the user select a query from a combo-box drop down menu, click a button, then the query results get displayed on the datagridview.
That is all working properly, however when a different query is selected and submitted, the datagridview displays additional empty columns used by the previously selected query.
What would be the best way to stop this from happening? is this based on the datagridview itself? or my subroutine to connect to the database and perform the query
I have tried clearing out the datatable(used in the query subroutine) and columns of the datagridview, but this has not solved the issue.
My various attempts at clearing the datagridview with a button (tried in various combinations):
Private Sub btnclearquery_Click(sender As System.Object, e As System.EventArgs) Handles btnclearquery.Click
mysql.qrydata.Clear()
DataGridViewqry.DataSource = Nothing
DataGridViewqry.Columns.Clear()
DataGridViewqry.Rows.Clear()
End Sub
My subroutine to perform the queries (referenced in another code file. sqlquery string is filled using select case when the user selects a query from the combo-box):
Public qrysqlconn As MySqlConnection
Public qrycommand As New MySqlCommand
Public qryadapter As New MySqlDataAdapter
Public qrydata As New DataTable
Public qrysql As String
Public Sub doquery(ByVal sqlquery As String)
qrysqlconn = New MySqlConnection
qrysqlconn.ConnectionString = "server=localhost;" _
& "user id=root;" _
& "password=W1nd0ws;" _
& "database=hystest"
qrysql = sqlquery
Try
qrysqlconn.Open()
qrydata.Clear()
qrycommand.Connection = qrysqlconn
qrycommand.CommandText = qrysql
qryadapter.SelectCommand = qrycommand
qryadapter.Fill(qrydata)
queries.DataGridViewqry.DataSource = qrydata
queries.DataGridViewqry.FirstDisplayedScrollingRowIndex = queries.DataGridViewqry.RowCount - 1
Catch myerror As MySqlException
MessageBox.Show("Database error: " & myerror.Message)
Finally
qrysqlconn.Close()
qrysqlconn.Dispose()
End Try
End Sub
I have had an issue like this before as well.
you may need to create a new instance of DataView for each new view you wish to display to get around this:
Dim dataview As DataView = _ds.YourStuff.DefaultView
dataview.Stuff
I managed to solve this, or at least create a work-around to the problem, by creating an individual subroutine/connection/datatable for each query. so instead of:
doquery(sql command)
I have used:
query1(<parameters>)
query2(<parameters>)
...
etc
This seems to work okay for now. this would imply that the issue was based on re-using the same datatable over and over again.