I get the same id number with transactions - sql-server

Hello i have a restaurant application i try to make a function to get transaction number for order but some times i get the same transaction number
Function GetTransNo() As String
Try
Dim sdate As String = Now.ToString("yyyyMMdd")
cn.Open()
cm = New SqlCommand("Select * From TblCart Where TransNo Like '" & sdate & "%' Order By Id Desc", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
GetTransNo = CLng(dr.Item("Transno").ToString) + 1
Else
GetTransNo = sdate & "0001"
End If
dr.Close()
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical)
GetTransNo = ""
End Try
Return GetTransNo
End Function
and this sub to get orders i get an empty table name and the same transaction number
Sub GetOrder()
Dim found As Boolean
Dim tno As String = ""
cn.Open()
cm = New SqlCommand("Select * From tblcart Where tableno like '" & LblTable.Text & "' and status like 'Pending'", cn)
dr = cm.ExecuteReader
dr.Read()
If dr.HasRows Then
found = True
tno = dr.Item("TransNo").ToString
Else
found = False
End If
dr.Close()
cn.Close()
If found = True Then
LblTransNo.Text = tno
loadcart()
End If
End Sub

Related

I get empty data on the datagridview

I'm trying to pass value from a SQL Server localdb database to a datagridview by textbox.
I use this code:
Public Sub InsertBarcode()
Dim x As Integer
Try
If Con.State = 1 Then Close()
Con.Open()
Dim cmd As New SqlCommand("Select * from Products where ProdBarCode=#ProdBarCode", Con)
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#ProdBarCode", SqlDbType.NVarChar).Value = TxtBarcode.Text
Dim adp As New SqlDataAdapter(cmd)
Dim dr As SqlDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
DataGridView1.Rows.Add()
x = DataGridView1.Rows.Count - 1
DataGridView1(0, x).Value = dr("ProdId").ToString
DataGridView1(1, x).Value = dr("ProdName").ToString
DataGridView1(2, x).Value = dr("QtyAvailable").ToString
DataGridView1(3, x).Value = dr("BuyPrice").ToString
End While
dr.Close()
Con.Close()
Else
MsgBox("There is no data")
End If
Catch ex As Exception
Con.Close()
End Try
End Sub
Private Sub TxtBarcode_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles
TxtBarcode.PreviewKeyDown
If e.KeyCode = Keys.Enter Then
InsertBarcode()
'TxtBarcode.Text = ""
End If
End Sub
I get just the first row and when I try to add another barcode or the same barcode, I get empty rows.
have you tried to use DataTable() instead of a While ... End While
Public Sub InsertBarcode()
Dim x As Integer
Try
If Con.State = 1 Then Close()
Con.Open()
Dim cmd As New SqlCommand("Select * from Products where ProdBarCode=#ProdBarCode", Con)
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#ProdBarCode", SqlDbType.NVarChar).Value = TxtBarcode.Text
Dim adp As New SqlDataAdapter(cmd)
Dim dr As SqlDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
'While dr.Read
' DataGridView1.Rows.Add()
' x = DataGridView1.Rows.Count - 1
' DataGridView1(0, x).Value = dr("ProdId").ToString
' DataGridView1(1, x).Value = dr("ProdName").ToString
' DataGridView1(2, x).Value = dr("QtyAvailable").ToString
' DataGridView1(3, x).Value = dr("BuyPrice").ToString
'End While
'dr.Close()
Dim dt As New DataTable()
dt.Load(dr)
dataGridView1.DataSource = dt
Con.Close()
Else
MsgBox("There is no data")
End If
Catch ex As Exception
Con.Close()
End Try
End Sub

VB.NET SQL Server: Must declare scalar variable

I am trying to make a query that deletes the user from my database.
But when i confirm to delete the user it gives me an error:
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "#Username".
Imports System.Data.SqlClient
Public Class DeleteForm
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim RetVal As Integer
Dim conn = New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbProject;Integrated Security=True")
Using cmd = New SqlCommand("select count(*) from tblLogin where username = #Username and password = #Password", conn)
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text
conn.Open()
If conn.State = ConnectionState.Open Then
RetVal = CInt(cmd.ExecuteScalar)
If RetVal = 1 Then
If txtPassword.Text And txtCheckPassword.Text <> "" Then
If txtCheckPassword.Text = txtPassword.Text Then
Dim cancConf As Integer = MessageBox.Show("This cant be undone!" & vbCrLf & "Are you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If cancConf = DialogResult.Yes Then
Try
Dim queryDelete As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdDelete As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.ExecuteNonQuery()
MsgBox("Account deleted succesfully!")
cmdCancellazione.Dispose()
conn.Close()
LoginForm.Show()
Me.Close()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
ElseIf cancConf = DialogResult.No Then
End If
Else
MsgBox("The passwords arent matching!", MsgBoxStyle.Exclamation)
End If
ElseIf txtPUtenteCANC.Text <> "" And txtPUtenteCONF.Text = "" Then
MsgBox("Please, confirm the password")
End If
Else
MsgBox("User not found!", MsgBoxStyle.Exclamation)
txtNUtenteCANC.Clear()
txtPUtenteCANC.Clear()
txtPUtenteCONF.Clear()
txtNUtenteCANC.Select()
End If
Else
MessageBox.Show("The connection is not open!" & vbCrLf & "The program will close", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End
End If
End Using
End Sub
End Class
You have added that parameter to the SELECT COUNT command but not to the DELETE command.
Dim queryCancellazione As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdCancellazione As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text

Controlling Excel through VB.NET [duplicate]

myConnection.Open()
rtb_Address.Clear()
txt_Name.Clear()
Dim str As String
str = "SELECT * FROM table1 WHERE (cus_ID = '" & txt_ID.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader()
While dr.Read()
rtb_Address.Text = dr("cus_Addr").ToString
txt_Name.Text = dr("cus_Name").ToString
End While
myConnection.Close()
Error in dr = cmd.ExecuteReader()
dr is declared as OleDbDataReader
cus_ID is probaly a numeric data type, but you try to query it with a string: (cus_ID = 'thevalue').
Just remove the enclosing ': (cus_ID = thevalue)
or better, use a parameterized query to prevent sql-injection.
I would recommend the following:
Using cmd As New OleDbCommand("SELECT * FROM table1 WHERE cus_ID = #ID", con)
cmd.Parameters.AddWithValue("#ID", txt_ID.Text)
dr = cmd.ExecuteReader()
While dr.Read()
rtb_Address.Text = dr("cus_Addr").ToString
txt_Name.Text = dr("cus_Name").ToString
End While
End Using

search read sql data to textbox in vb

it show even when i have data inside my database[invalid attempt to read when no data is present]
i was hoping to show details in textbox with txtid.text inserted
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
Try
con.ConnectionString = "Server=KAVIER;Database=vb;Trusted_Connection=True;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM music where mus_id = '" & txtid.Text & "' "
rd = cmd.ExecuteReader() 'corrected my previous mistake
If rd.HasRows Then
txtartist.Text = rd.Item("customer")
txtid.Text = rd.Item("album")
txtgenre.Text = rd.Item("genre")
hided.Text = rd.Item("music_copies")
txtprice.Text = rd.Item("price")
txttotal.Text = txtprice.Text * txtwalkinquantities.Text
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
cmd.CommandText = "SELECT * FROM music where mus_id = '" & txtid.Text & "' "
rd = cmd.ExecuteReader()
If rd.read Then
txtartist.Text = rd.Item("customer")
txtid.Text = rd.Item("album")
txtgenre.Text = rd.Item("genre")
hided.Text = rd.Item("music_copies")
txtprice.Text = rd.Item("price")
txttotal.Text = txtprice.Text * txtwalkinquantities.Text
End If
replace rd.HasRows with rd.read

OdbcDataAdapter Fill function not giving output if we show record from temperary table (#temp)

I am using below code to retrive data from table using stored procedure :
Dim Pars(0) As OdbcParameter
Pars(0) = New OdbcParameter("#UserID", OdbcType.VarChar)
Pars(0).Value = usrid
Pars(0).Direction = ParameterDirection.Input
Dim UserTbl As DataTable = Nothing
UserTbl = DBAccess.RunStoredProcedureDttbl("USP_GET_Data", Pars)
Below function giving output in SYSBASE database but no record found in case of SQL SERVER DB
Public Overloads Shared Function RunStoredProcedureDttbl(ByVal ProcedureName As String, ByVal pars() As OdbcParameter) As DataTable
Try
Dim dt As New DataTable
If Cmd.Parameters.Count > 0 Then
Cmd.Parameters.Clear()
End If
Con = New OdbcConnection(ConnectionString)
Con.Open()
dt.Clear()
Cmd = New OdbcCommand(" {call " & ProcedureName & PrepareParameters(pars), Con)
Cmd.CommandType = CommandType.StoredProcedure
For Each par As OdbcParameter In pars
Cmd.Parameters.Add(par)
Next
Cmd.Connection = Con
Cmd.CommandTimeout = 0
OdbcAd = New OdbcDataAdapter(Cmd)
OdbcAd.Fill(dt)
Return dt
Catch ex As OdbcException
Throw New ArgumentException(ex.Message)
Catch ex As Exception
Throw New ArgumentException("DAL\\DrDAL\\RunStoredProcedureWithParameters\\ " & ex.Message)
Finally
Con.Dispose()
DisposeObjects()
End Try
End Function
I tried below function working fine in both database
Public Overloads Shared Function RunStoredProcedureDtOut(ByVal ProcedureName As String, ByVal pars() As OdbcParameter) As DataTable
Try
Dim dt As New DataTable
If Cmd.Parameters.Count > 0 Then
Cmd.Parameters.Clear()
End If
Cmd = New OdbcCommand(" {call " & ProcedureName & PrepareParameters(pars), Con)
Cmd.CommandType = CommandType.StoredProcedure
Cmd.CommandTimeout = 0
For Each par As OdbcParameter In pars
Cmd.Parameters.Add(par)
Next
OdbcDr = Cmd.ExecuteReader()
dt.Load(OdbcDr)
Return dt
Catch ex As OdbcException
Throw New ArgumentException(ex.Message)
Catch ex As Exception
Throw New ArgumentException("DAL\\DrDAL\\RunStoredProcedureWithParameters\\ " & ex.Message)
Finally
OdbcDr.Close()
Con.Dispose()
End Try
End Function
What is reason? Why "OdbcAd.Fill(dt)" not working in SQL SERVER DB ?
Code for PrepareParameters
Private Shared Function PrepareParameters(ByVal pars() As OdbcParameter) As String
Try
Dim s As String = " (?"
Dim i As Byte = 0
If pars.Length >= 2 Then
For i = 0 To pars.Length - 2
s = s + ",?"
Next i
End If
s = s + ")}"
Return s
Catch ex As OdbcException
Throw New ArgumentException(ex.Message)
Catch ex As Exception
Throw New ArgumentException("PrepareParameters\\ " & ex.Message)
End Try
End Function
First function showing records when I remove temperary table from Store procedure.If I store data in temperary table (#temp) and then display record.It result into zero record.
Can anyone tell me reason ?

Resources