sqldatabase variable declaration from a listbox in Vb.net 2010 - sql-server

I'm trying to save the selected Item from the listbox to the database but when i choose the item from the listbox I get a Runtime error that the variable(RomID) is not declared. Here's the code. What am I missing?!
If (con.State = ConnectionState.Closed) Then
con.Open()
End If
Dim Name As SqlParameter = New SqlParameter("#Name", TxtName.Text)
Dim Pass As SqlParameter = New SqlParameter("#PassportNum", TxtPassNum.Text)
Dim Mobile As SqlParameter = New SqlParameter("#PhoneNUm", TxtMobile.Text)
Dim RomID As SqlParameter = New SqlParameter("#ID", Integer.Parse(ListBox1.SelectedItem))
Dim ChckIn As SqlParameter = New SqlParameter("#CheckIndate", DateTime.Now.Date)
Dim Email As SqlParameter = New SqlParameter("#Email", TxtEmail.Text)
Cmd.Parameters.Add(Name)
Cmd.Parameters.Add(Pass)
Cmd.Parameters.Add(Mobile)
Cmd.Parameters.Add(RomID)
Cmd.Parameters.Add(ChckIn)
Cmd.Parameters.Add(Email)
Cmd.CommandText = "Update Rooms set Status ='Booked' where ID = #RomID"
Cmd.ExecuteNonQuery()
Cmd.CommandText = "insert into Reservation(RoomID,GuestName,PassportNum,PhoneNUm,CHeckIndate,Email) VALUES(#RomID,#Name,#Pass,#Mobile,#ChckIn,#Email)"
Cmd.ExecuteNonQuery()
MessageBox.Show("Reservation Was Successful")

I have not declared in the same way can you try this:
remove:
Dim RomID As SqlParameter =
New SqlParameter("#ID", Integer.Parse(ListBox1.SelectedItem))
try something like this :
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = Integer.Parse(ListBox1.SelectedItem)

You have this:
Dim RomID As SqlParameter =
New SqlParameter("#ID", Integer.Parse(ListBox1.SelectedItem))
I think you meant this:
Dim RomID As SqlParameter =
New SqlParameter("#RomID", Integer.Parse(ListBox1.SelectedItem))

Related

SqlParameter not supplied when using Parameters.AddWithValue

This is how I set up my command. It stops with the first parameter, UpdateType. This code is being updated from VB.NET 2008 version.
Dim db As New DB()
Dim cmd As SqlCommand = New SqlCommand()
'Put into an object, and use AddWithValue due to Parameters.Add being deprecated.
Dim UpdateType As String = "PARAMETERS"
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.AddWithValue("#UpdateType", SqlDbType.NVarChar).Value = UpdateType
cmd.Parameters.AddWithValue("#OrigJobName", OrigJobName.ToString)
End If
cmd.Parameters.AddWithValue("#UserID", CInt(Utils.GetLoggedInUserID))
cmd.Parameters.AddWithValue("#ProjectName", ProjectName.ToString)
You should use .Add instead with the type and for NVARCHAR, VARCHAR, or VARBINARY
with the length. Here I show how to do the tings you have in the question, I made up lengths just for the example. Using AddWithValue can have negative impact on SQL performance and other things.
Some information to help you can be found in many places including here https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types
Dim db As New DB()
Dim cmd As SqlCommand = New SqlCommand()
Dim UpdateType As String = "PARAMETERS"
cmd.CommandType = CommandType.StoredProcedure
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.Add("#UpdateType", SqlDbType.NVarChar, 10).Value = UpdateType
cmd.Parameters.Add("#OrigJobName", SqlDbType.NVarChar, 50).Value = OrigJobName.ToString
End If
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = CInt(Utils.GetLoggedInUserID)
cmd.Parameters.Add("#ProjectName", SqlDbType.NVarChar, 30).Value = ProjectName.ToString
Keep your database objects local to the method where they are used so you can control that they are closed and disposed. `Using...End Using blocks take care of this for you. Note a single Using block is handling both the connection and the command.
The .Add method is NOT being deprecated. What is obsolute is the .Add(String, Object) overload. `.AddWithValue is certainly out of favor. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
I had to guess at the datatype and column size of your parameters. Check your database for the actual values and correct the code accordingly.
Private Sub OpCode()
Dim UpdateType As String = "PARAMETERS"
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.Add("#UpdateType", SqlDbType.NVarChar, 50).Value = UpdateType
cmd.Parameters.Add("#OrigJobName", SqlDbType.NVarChar, 200).Value = OrigJobName.ToString
End If
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = CInt(Utils.GetLoggedInUserID)
cmd.Parameters.Add("#ProjectName", SqlDbType.NVarChar, 200).Value = ProjectName.ToString
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Populate Combobox from SQL Server vb.net

I'm trying to populate a combobox with data from SQL Server. This is my code so far. There are asterisks around the errors. Also, ignore the comments.
Private Sub frmOriginal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connetionString As String = Nothing
Dim sqlcon As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
connetionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
sql = "select * from TickerSymbol"
sqlcon = New SqlConnection(connetionString)
Try
sqlcon.Open()
command = New SqlCommand(sql, sqlcon)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
sqlcon.Close()
cboID.DataSource = ds.Tables(0)
cboID.ValueMember = "TickerSymbol"
cboID.DisplayMember = "TickerSymbol"
Catch ex As Exception
'MessageBox.Show("Can not open connection ! ")'
End Try
End Sub
Private Sub cboID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboID.SelectedIndexChanged
Dim dr As SqlDataReader
Dim command As New SqlCommand *(queryString, connection)*
Dim dataReader As SqlDataReader = command.ExecuteReader()
Dim sqlcon As SqlConnection
Dim cmd As SqlCommand
sqlcon = New SqlConnection
sqlcon.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
Try
sqlcon.Open()
cmd = New SqlCommand
cmd.CommandText = " select * from TickerSymbol where TickerSymbol = '" & cboID.Text & "'"
cmd = New SqlCommand(cmd.CommandText, sqlcon)
dr = cmd.ExecuteReader
While dr.Read()
'TxtID.Text = dr.GetInt32(0)'
'TxtSN.Text = dr.GetString(1)'
'TxtGender.Text = dr.GetString(2)'
'TxtPhone.Text = dr.GetInt32(3)'
'TxtAdrress.Text = dr.GetString(4)'
lblCompanyName.Text = dataReader.GetString(1)
lblPurchasePrice.Text = dataReader.GetSqlMoney(2)
lblQtyPurchased.Text = dataReader.GetInt32(3)
lblPurchaseDate.Text = dataReader.GetDateTime(4)
End While
sqlcon.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
sqlcon.Dispose()
End Sub
Please use parameterized queries as this will format values properly e.g. apostrophes in text will escape properly with parameters while without you must handle them, dates will be formatted properly too. Code is much cleaner also.
Example, syntax for Framework 3.5 and higher. If a connection string is used more than once then consider placing it in a private variable or under My.Settings under project properties.
Using cn As New SqlConnection With {.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"}
Using cmd As New SqlCommand With {.Connection = cn, .CommandText = "select * from TickerSymbol where TickerSymbol = #TickerSymbol"}
cmd.Parameters.AddWithValue("#TickerSymbol", cboID.Text)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
'
'
'
End While
End If
End Using
End Using

Populating ListBox using parameterized query on VB.Net

I have the following code that involves populating a ListBox. How can I parameterize the query to prevent SQL injection?
sqlCon = New SqlConnection(strConn)
sqlCon.Open()
Dim sql As String = "SELECT * FROM employees where id = & textbox1.text &"
Dim adapter As New SqlDataAdapter(sql, sqlCon)
Dim da As New DataTable
adapter.Fill(da)
ListBox1.DisplayMember = "employees"
ListBox1.DataSource = da
ListBox1.ValueMember = "employees"
sqlCon.Close()
Maybe this will help:
Using sqlCon As SqlConnection = New SqlConnection(strConn)
sqlCon.Open()
Dim sql As String = "SELECT * FROM employees WHERE id = #id"
Dim adapter As SqlDataAdapter = New SqlDataAdapter(sql, sqlCon)
adapter.SelectCommand.Parameters.Add(New SqlParameter("#id", textbox1.Text))
Dim da As New DataTable
adapter.Fill(da)
ListBox1.DisplayMember = "employees"
ListBox1.DataSource = da
ListBox1.ValueMember = "employees"
End Using
It's better to enclose the code inside the Using so that the SqlConnection will be disposed even an exception is thrown. Also instead of using SELECT *, you may want to specify the column names.

Microsoft SQL Server SELECT statement

I need help retrieving ReceiptNO column from a database table and saving it into a TextBox or Label for referencing.
CODE:
Dim da2 As New SqlDataAdapter
da2.SelectCommand = New SqlCommand("SELECT RecepitNO FROM Receipt WHERE (PaidFor=#PaidFor AND RegNO=#RegNO)")
da2.SelectCommand.Parameters.Add("#paidFor", SqlDbType.VarChar).Value = cbMonth.Text
da2.SelectCommand.Parameters.Add("#RegNO", SqlDbType.Int).Value = lblRegNO.Text
cn.Open()
da2.Update(ds.Tables("Receipt"))
'da2.SelectCommand.ExecuteNonQuery()
da2.SelectCommand.ExecuteReader()
cn.Close()
You need to use a SqlDataReader, and then start a loop to read the values returned
This example will work assuming the ReceiptNO is a text field
cn.Open()
Dim reader = da2.SelectCommand.ExecuteReader()
while reader.Read()
textBox1.Text = reader("ReceiptNO").ToString()
End While
In alternative, if you are sure that your query returns zero or just one record and you are interested only in the ReceiptNO field, then you can use ExecuteScalar
Dim cmd = New SqlCommand("SELECT RecepitNO FROM Receipt WHERE (PaidFor=#PaidFor AND RegNO=#RegNO)")
cmd.Connection = cn
cmd.Parameters.Add("#paidFor", SqlDbType.VarChar).Value = cbMonth.Text
cmd.Parameters.Add("#RegNO", SqlDbType.Int).Value = lblRegNO.Text
cn.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
textBox1.Text = result.ToString()
End If
Here the MSDN docs on ExecuteScalar

delete selected row from gridview and and update databse in vb.net windows form

I have a Delete button and i am trying to delete selected rows from gridview and database by clicking on that button. but having following code i am getting error like Argument out of range and convert to int.
Private Sub dltButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dltButton.Click
'Dim StudentId As String
'StudentId =
'con.Open()
'cmd.CommandText = "delete from KaiyumVbStudent where StudentID = '"&StudentId&"'"
'cmd.Connection = con
Dim i As Integer = DataGridView1.SelectedRows(0).Index
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0))
con = New SqlConnection(constring)
con.Open()
Me.StudentID = Convert.ToInt32(DataGridView1.SelectedRows(0).Index)
cmd = New SqlCommand("Delete from KaiyumVbStudent where StudentID = '#StudentID'", con)
cmd.ExecuteNonQuery()
Call databind()
Private Sub databind()
con = New SqlConnection(constring)
con.Open()
cmd = New SqlCommand("Select *from KaiyumVbStudent", con)
Dim dr As SqlDataReader = cmd.ExecuteReader()
dt = New DataTable()
dt.Load(dr)
Me.DataGridView1.DataSource = dt
End Sub
First put our code in try catch statement and check student Id datatype
Your are missing one statement
cmd.Parameters.AddWithValue("#StudentID", StudentID);
I hope you it is work..

Resources