Populating ListBox using parameterized query on VB.Net - sql-server

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.

Related

How to Parameterized Queries with the SqlDataSource (VB)

This is my code example to run parameterized query in VB.NET:
Dim sqlconn As New SqlConnection(connectionString)
sqlconn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Select * from TAble1 Where SkuCode in (#SKU)"
cmd.Connection = sqlconn
Dim parm As New SqlParameter
parm.Value ="1" 'This is working
parm.ParameterName = "#SKU"
cmd.Parameters.Add(parm)
Dim ds As New DataSet
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(ds)
Dim dt As DataTable
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
MsgBox("Done")
Else
MsgBox("Not done.")
End If
If I run this example in VB.NET this returns the result successfully.
But there is an issue while trying to get results with multiple in records... this is not working.
Please check and suggest the change we have to do to run in query with parameters.
'parm.Value = "N'1', N'2'" 'this does not work.
'parm.Value = "'1','2'" 'this does not work.
I have tried these parameter value but it does not work.
SQL parameters are scalar and only accept a single value. You can use the sqldbtype.Structured though it gets a bit complicated.
I've found that if you need to pass in a set of parameters for an IN where the number of parameters is dynamics, the most effective way (unfortunately) is:
String interpolation/concatenation without parameters
Loop to build out the parameters and add them to your sqlcommand
LINQ to build out the parameters and add them to your sqlcommand
I've provided an example of the linq option below.
Dim sqlParams As Dictionary(Of String, Integer) = integers.ToDictionary(Function(i) $"#ParamValue{i}", Function(i) i)
Dim ds As New DataSet
Dim dt As DataTable
Using db as new SqlConnection(conn)
conn.open()
Using cmd As New SqlCommand($"SELECT * FROM Table1 WHERE SkuCode IN (-1, {String.Join(", ", sqlParams.Select(Function(f) f.Key))}", db)
cmd.Parameters.AddRange(sqlParams.Select(Function(f) New SqlParameter(f.Key, SqlDbType.BigInt).Value = f.Value).ToArray())
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(ds)
dt = ds.Tables(0)
End Using
End Using
MsgBox(If(dt.Rows.Count > 0, "Done", "Not done"))

Datagridview show no data vb.net with SQL Server

Public Sub LoadAllTable_Items_InDirect(ByVal dgv As DataGridView, ByVal calstate As String)
Dim dt As New DataTable
Dim da As New SqlDataAdapter
dt.Clear()
da = New SqlDataAdapter("select * from ItemsView where " & calstate & " = 'True'", sql.sqlcon)
da.Fill(dt)
dgv.AutoGenerateColumns = False
dgv.DataSource = dt
End Sub
Here is a sample code to bind the datagridview in VB.Net you can compare and correct if any part is missing in your code.
I think you are missing the code of add columns part as shown in my sample code.
Private Sub BindGrid()
Dim constring As String = "Data Source=.\SQL2005;Initial Catalog=Northwind;User id = sa;password=pass#123"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("SELECT * FROM Customers", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
'Set AutoGenerateColumns False
dataGridView1.AutoGenerateColumns = False
'Set Columns Count
dataGridView1.ColumnCount = 3
'Add Columns
dataGridView1.Columns(0).Name = "CustomerId"
dataGridView1.Columns(0).HeaderText = "Customer Id"
dataGridView1.Columns(0).DataPropertyName = "CustomerID"
dataGridView1.Columns(1).Name = "Name"
dataGridView1.Columns(1).HeaderText = "Contact Name"
dataGridView1.Columns(1).DataPropertyName = "ContactName"
dataGridView1.Columns(2).Name = "Country"
dataGridView1.Columns(2).HeaderText = "Country"
dataGridView1.Columns(2).DataPropertyName = "Country"
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Using
End Sub

Filling multi tables into dataset?

I have problem with my code which fills multi tables into my dataset. It loads all contents contained in tables of my database to only one table in dataset. My code is shown below. How to load those tables from database into a dataset , that has the same number of tables and contents.
Private Sub Filldataset()
Private cnn As OleDbConnection
Private dt As New DataTable
Private da As New OleDbDataAdapter
Private cmd As New OleDbCommand
Private ds As New DataSet
Dim tblrestrictions As String() = New String() {Nothing, Nothing, Nothing, "TABLE"}
Dim userTables As DataTable = Nothing
userTables = cnn.GetSchema("Tables", tblrestrictions)
Dim i As Integer
For i = 1 To userTables.Rows.Count - 1 Step 1
cnn = New OleDbConnection(Str)
cnn.Open()
cmd = cnn.CreateCommand
cmd.CommandText = "select * from" & " " & userTables.Rows(i)(2).ToString
dt.Clear()
da.SelectCommand = cmd
da.Fill(dt)
da.Fill(ds)
Next
cnn.Close()
MessageBox.Show(ds.Tables.Count)
End Sub
Connections can be created elsewhere but should not be opened or closed until directly before an directly after you use them. You will have to adjust this code for an Oledb application.
Private Sub GetData()
cn.Open()
Dim dt As DataTable = cn.GetSchema("Tables")
cn.Close()
Dim ds As New DataSet
Dim row As DataRow
For Each row In dt.Rows
Dim strTableName As String = row(2).ToString
Dim strSQL As String = "Select * From " & strTableName
Dim cmd As New SqlCommand(strSQL, cn)
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
da.Fill(ds, strTableName)
Next
Debug.Print(ds.Tables.Count.ToString)
End Sub
I scoped several variables locally that you will want to scope to the class like the dataset

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I've been trying to view a table in a datagridview by using a the table name chosen in combobox but I still get the error
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
I don't know what is wrong.
This is my code
Dim myconnection As New SqlConnection("data source=.\sqlexpress; initial catalog=itses;integrated security=true")
Dim da As New SqlDataAdapter
Dim source1 As New BindingSource
Dim table As New DataTable
Dim ds As New DataSet
myconnection.Open()
Dim query As String
query = "Select * from '" & ComboBox6.SelectedItem & "'"
mycommand = New SqlCommand(query, myconnection)
da.SelectCommand = mycommand
da.Fill(table)
source1.DataSource = table
DataGridView2.DataSource = source1
da.Update(table)
myconnection.Close()
Most likely, it's just the unneeded single quotes around the table name you're using - try this instead:
Dim query As String
query = "Select * from " & ComboBox6.SelectedItem
The query should be
Select * from TableName
(without any single quotes or anything else around the table name)
have you tried adding ToString() and removing '' like so
query = "Select * from "& ComboBox6.SelectedItem.ToString() &""
or just the SelectedItem should work
query = "Select * from "& ComboBox6.SelectedItem &""

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

Resources