How to populate datagridview with dataset from select query? - vb.net

I'm making a search bar using SELECT query and I want to transfer the results to a DataGridView. But I always get an empty DataGridView.
Nothing is wrong with the query, I already tried to input it manually in access. What am I doing wrong in the code? Here it is:
Using conn = New OleDbConnection(connstring)
Try
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"
Dim da As New OleDbDataAdapter(Sql, conn)
Dim ds As New DataSet
da.Fill(ds)
DataGridView2.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
End Using

The issue is as I stated in the comment. ADO.Net uses the % for the like to maintain consistency with most major Sql engines. But I would like to point out that your query is unsafe and subject to SQL injection so I have included an example of your code using a parameter to pass user input to the command.
Also note that the OleDbDataAdapter can be declared in a Using statement the same way you did with the OleDbConnection Note that you may however have to widen the scope of the dataset (ds) if you plan on doing other things with it.
Using conn As OleDbConnection = New OleDbConnection(connstring)
Try
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE #Product"
Using da As OleDbDataAdapter = New OleDbDataAdapter(Sql, conn)
da.SelectCommand.Parameters.Add("#Product", OleDbType.Varchar).Value = txtSearchProduct.Text & "%"
Dim ds As New DataSet
da.Fill(ds)
DataGridView2.DataSource = ds.Tables(0)
End Using
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
End Using

Like Charles has mentioned its always better to use parameters. My answer is a bit different whereas it uses a reader and not an adapter, and a datatable and not an entire dataset. An adapter should only be used if you intend to write back to the table, or typical scenarios include binding procedures. A DataSet is typically used when you have multiple tables and have a need to relate them. Also note, you most likely want a preceding % in your parameter if you want to match the string regardless of the position in the search column.
Try
Using conn = New OleDbConnection("YourConnString")
conn.Open()
Dim Cmd As New OleDbCommand("SELECT * FROM Products WHERE [Product Name] LIKE #Product", conn)
Cmd.Parameters.AddWithValue("#Product", "'%" & txtSearchProduct.Text & "%'")
Dim ProductsRDR As OleDbDataReader = Cmd.ExecuteReader
Dim DTable As New DataTable With {.TableName = "Products"}
DTable.Load(ProductsRDR)
DataGridView1.DataSource = DTable
conn.Close()
End Using
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try

All you have to do is replacing the * sign with % in your Sql string, just like this:
This is your wrong Sql string:
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"
Change it to this:
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "%'"

This should cover most of the common scenarios out there.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

Related

Adapter update statement in oledb

I have a form with retrieved data form ms access database. While updating using the adapter update statement, it shows Syntax error.
The following are the connection code in form load event and update button click event.
could you please let me know whats wrong in this?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Dim Con As New OleDbConnection()
Dim Cmd As New OleDbCommand
Dim SQL As String = "SELECT * FROM Heidelberg"
Con.ConnectionString = strConn
Try
Con.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Cmd = New OleDbCommand(SQL, Con)
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
ds = New DataSet
Adapter.Fill(ds, "testing")
MaxRows = ds.Tables("testing").Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim cb As New OleDb.OleDbCommandBuilder(Adapter)
ds.Tables("testing").Rows(inc).Item(5) = TextBox1.Text
ds.Tables("testing").Rows(inc).Item(2) = TextBox2.Text
ds.Tables("testing").Rows(inc).Item(3) = TextBox3.Text
ds.Tables("testing").Rows(inc).Item(4) = TextBox4.Text
Try
Adapter.Update(ds, "testing")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You have way too many commands in your Form.Load.
One
Dim Cmd As New OleDbCommand
Two
Cmd = New OleDbCommand(SQL, Con)
Three
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
Every time you use the New keyword, you create another command.
If you are only dealing with a single table, you don't need a DataSet. The extra object adds extra weight and complicates the code a bit.
Private inc As Integer
Private Adapter As New OleDbDataAdapter
Private MaxRows As Integer
Private dat As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Using Con As New OleDbConnection(strConn)
Using Cmd As New OleDbCommand("SELECT * FROM Heidelberg;", Con)
Adapter.SelectCommand = Cmd
Try
Adapter.Fill(dat)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
MaxRows = dat.Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
dat.Rows(inc).Item(5) = TextBox1.Text
dat.Rows(inc).Item(2) = TextBox2.Text
dat.Rows(inc).Item(3) = TextBox3.Text
dat.Rows(inc).Item(4) = TextBox4.Text
Dim cb As New OleDbCommandBuilder(Adapter)
'This will take care of any spaces that you have in column names.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Try
Adapter.Update(dat)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

How to search data from textbox and fill specific columns of datagridview from SQL database?

I am trying to search itemcode by typing in textbox and i want to get specific columns in same row from SQL database. I have made columns with headers in datagridview and i want that searched data in that specific datagridview columns. I have written code but it's not working. I do not know how to do this. I am new and trying to learn vb. Please give some suggestion.
This is my code:
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
Using cn As New SqlConnection("server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=true")
Using cmd2 As New SqlCommand("select itemcode As 'Item Code', item,qty As Quantity, weight as Weight from stockdata Where itemcode = #itemcode;", cn)
cmd2.Parameters.AddWithValue("#itemcode", TextBox1.Text)
cn.Open()
Dim dr As SqlDataReader = cmd2.ExecuteReader()
dt.Load(dr)
DataGridView1.DataSource = dt
For Each row As DataGridViewRow In DataGridView1.Rows
cmd2.Parameters.Add("#item", SqlDbType.VarChar)
cmd2.Parameters.Add("#qty", SqlDbType.VarChar)
cmd2.Parameters.Add("#weight", SqlDbType.VarChar)
With cmd2
row.Cells(1).Value = .Parameters("#item").Value
row.Cells(2).Value = .Parameters("#qty").Value
row.Cells(2).Value = .Parameters("#weight").Value
End With
cmd2.ExecuteNonQuery()
Next
End Using
End Using
End Sub
I used a TextBox located outside the DataGridView to enter the item code to search for. I added a Button to do the search and retrieve the data to a DataReader.
The DataReader then loads the DataTable which is declared as a form level (class level variable). We want to use the same DataTable every time we search so the items will be added to the grid. With the Load method if the DataTable already contains rows, the incoming data from the data source is merged with the existing rows. The DataTable is then bound to the DataGridView. Each time the user enters an item code in the TextBox and clicks the Search Button a new row will be added to the grid.
To make nicer looking Column headers use as alias in your Select statement. The As clause following the databse column name is the alias and will show up in the DataGridView as a header. If you have a space in your alias it must be enclosed in single quotes.
Private dt As DataTable
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dt = New DataTable()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Using cn As New SqlConnection("server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=true")
Using cmd2 As New SqlCommand("select itemcode As 'Item Code', item,qty As Quantity, weight as Weight from stockdata Where itemcode = #itemcode;", cn)
cmd2.Parameters.AddWithValue("#itemcode", txtItemCode.Text)
cn.Open()
Dim dr As SqlDataReader = cmd2.ExecuteReader()
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
End Using
End Sub
P.S. Very glad to see the use of parameters and Using blocks! :-)
I saw several things to check:
When you use a datasource, you don't need to loop through the rows of your reader.
Check the connection string (is "pankaj billing software" really the name of the database? They don't usually have spaces)
You want square brackets ([] or double quotes ") rather than single quotes (') for the column name in the SQL statement.
It's also best to avoid the AddWithValue() function in favor of calling Add() with the exact column type and length.
We don't see where dt is declared.
Put it all together (guessing at column name/length, and haven't changed the database name yet) and you get this:
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
Dim sql = "select itemcode As [Item Code], item, qty As Quantity, weight as Weight from stockdata Where itemcode = #itemcode;"
Dim dt As New DataTable()
Using cn As New SqlConnection("server=PANKAJ\SQLEXPRESS;database=pankaj billing software;integrated security=true"), _
cmd2 As New SqlCommand(sql, cn)
cmd2.Parameters.Add("#itemcode", SqlDbType.NVarChar, 10).Value = TextBox1.Text
cn.Open()
Using dr As SqlDataReader = cmd2.ExecuteReader()
dt.Load(dr)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
But the big thing is "Not working" in never enough information about your code. What did you actually see that was different than what you expected? If there was an error message, what did it say exactly?
This is my script code:
protected void search_click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(conn);
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand cmd = new SqlCommand("spSearchUser", sqlCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#SearchTerm", "username");
cmd.Parameters.AddWithValue("#Username", txtSearch.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
searchBind();
GridView1.Visible = true;
txtSearch.Text = "";
}
}
This is WebForm code:
<div>
<table>
<tr>
<td>Search</td>
<td>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSearch" runat="server" Text="Go" onclick="search_click" />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
This is my Store Procedure:
alter procedure spSearchUser
(
#SearchTerm nvarchar(50),
#Username nvarchar(50)
)
as
begin
set nocount on;
if #SearchTerm = 'username'
begin
select Username,City,Gender,Email from tblRegistration where Username
LIKE '%' + #Username + '%'
end
end
How about this?
'"C:\your_path\Northwind.mdb"
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Windows.Forms
Public Class Form1
Inherits System.Windows.Forms.Form
Private bindingSource1 As New BindingSource()
Private dataAdapter As New OleDbDataAdapter()
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\your_path\Northwind.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
selectCommand = "Select * From MyExcelTable ORDER BY ID"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, btnUpdate.Click
Dim table As New DataTable()
Me.bindingSource1 = Me.DataGridView1.DataSource
table = Me.bindingSource1.DataSource
Me.dataAdapter.Update(table)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click, btnClose.Click
Me.Close()
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\your_path\Northwind.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '%" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
End Class

How to feed results of SQL statement into a GridView, not the SQL statement itself?

This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form

Parameters.AddWithValue: Parameter has already been defined

I try to add a parameters.addwithvalue.
Before change the code is like that..........
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
Me.Cursor = Cursors.WaitCursor
MysqlConn.Close()
MysqlConn.Open()
COMMAND.CommandText = "select logo from licenses where name = '" & ComboBox7.Text & "'"
COMMAND.Connection = MysqlConn
Dim da As New MySqlDataAdapter(COMMAND)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
If IsDBNull(ds.Tables(0).Rows(c - 1)("logo")) = True Then
PictureBox6.Image = Nothing
Else
Dim bytBLOBData() As Byte = ds.Tables(0).Rows(c - 1)("logo")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox6.Image = Image.FromStream(stmBLOBData)
End If
End If
Me.Cursor = Cursors.Default
End Sub
Now what i try this to add paramatrers.addwithValue without succes:
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
Me.Cursor = Cursors.WaitCursor
MysqlConn.Close()
MysqlConn.Open()
'COMMAND.CommandText = "select logo from licenses where name = '" & ComboBox7.Text & "'"
COMMAND.CommandText = "select logo from licenses where name = #ComboBox7Select"
COMMAND.Parameters.AddWithValue("#ComboBox7Select", If(String.IsNullOrEmpty(ComboBox7.Text), DBNull.Value, ComboBox7.Text))
COMMAND.Connection = MysqlConn
Dim da As New MySqlDataAdapter(COMMAND)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
If IsDBNull(ds.Tables(0).Rows(c - 1)("logo")) = True Then
PictureBox6.Image = Nothing
Else
Dim bytBLOBData() As Byte = ds.Tables(0).Rows(c - 1)("logo")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox6.Image = Image.FromStream(stmBLOBData)
End If
End If
Me.Cursor = Cursors.Default
End Sub
With error "Parameter '#ComboBox7Select' has already been defined."
What i do to change for work ??
Thanks you.
Don't store the MySqlConnection and MySqlCommand as fields in your class, don't reuse them at all. That's just a source of errors without any benefit. Create, initialize, use and dispose(Using-statement)them wherever you need them, so in this method.
You don't clear the parameters, that's why you get this error on second use.
So a simple COMMAND.Parameters.Clear() before you add it would solve the issue. But use the approach i have mentioned above:
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
Dim ds As New DataSet()
Dim licenseNameValue As Object = DBNull.Value
If Not String.IsNullOrEmpty(ComboBox7.Text) Then licenseNameValue = ComboBox7.Text
Using mysqlConn As New MySqlConnection("ConnectionString...")
Using da As New MySqlDataAdapter("select logo from licenses where name = #licenseName", mysqlConn)
da.SelectCommand.CommandText = "select logo from licenses where name = #licenseName"
da.SelectCommand.Parameters.AddWithValue("#licenseName", licenseNameValue)
da.Fill(ds, "projectimages") ' you dont need to open/close the connection with DataAdapter.Fill
End Using
End Using
' ....
End Sub
The problem is that you are using a global variable COMMAND that you use each time the selected index changes in your combo. Either you initialize the command each time with:
COMMAND=New MySqlCommand()
Or you must clear the parameters:
COMMAND.Parameters.Clear()
COMMAND.Parameters.AddWithValue("#ComboBox7Select", If(String.IsNullOrEmpty(ComboBox7.Text), DBNull.Value, ComboBox7.Text))
But the best way is always create and dispose the MySql objects with the Using struct:
Using MysqlConn As New MySqlConnection(connString)
Using COMMAND As New MySqlCommand()
'your code
End Using
End Using

VB.Net SQL Count Statement into a label

I'm trying to count the students whose teacher where teacher = '" & lblTeacher.Text & "'"
EXAMPLE :
Public Class Form1
Dim conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Richard\Desktop\Dbase.mdb"
Dim con As New OleDbConnection
Dim da, da1 As New OleDbDataAdapter
Dim dt, dt1 As New DataTable
Dim sql As String
Dim ds As New DataSet
Public Sub display()
sql = "select * from Info"
dt.Clear()
con.Open()
da = New OleDbDataAdapter(sql, con)
da.Fill(dt)
con.Close()
DataGridView1.DataSource = dt.DefaultView
End Sub
Public Sub count()
sql = "select COUNT(name) from Info where teacher = '" & lblTeacher.Text & "'"
da1 = New OleDbDataAdapter(sql, con)
ds.Clear()
con.Open()
da.Fill(ds)
lblCount.Text = ds.Tables(0).Rows.Count.ToString
con.Close()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = conn
display()
End Sub
Private Sub DataGridView1_Click(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Click
lblTeacher.Text = DataGridView1.CurrentRow.Cells("teacher").Value.ToString
count()
End Sub
End Class
1:
Try this instead of your current count() method. Pay special attention to my comments; they address some poor practices from the original code:
' Better functional style: accept a value, return the result
Public Function GetStudentCount(teacher As String) As Integer
'**NEVER** use string concatenation to put data into an SQL command!!!
Const sql As String = "select COUNT(name) from Info where teacher = ?"
'Don't try to re-use the same connection in your app.
' It creates a bottleneck, and breaks ADO.Net's built-in connection pooling,
' meaning it's more likely to make object use *worse*, rather than better.
'Additionally, connection objects should be created in a Using block,
' so they will still be closed if an exception is thrown.
' The original code would have left the connection hanging open.
Using con As New OleDbConnection(conn), _
cmd As New OleDbCommand(sql, con)
'This, rather than string concatenation, is how you should put a value into your sql command
'Note that this NEVER directly replaces the "?" character with the parameter value,
' even in the database itself. The command and the data are always kept separated.
cmd.Parameters.Add("teacher", OleDbType.VarChar).Value = teacher
con.Open()
' No need to fill a whole dataset, just to get one integer back
Return DirectCast(cmd.ExecuteScalar(), Integer)
'No need to call con.Close() manually. The Using block takes care of it for you.
End Using
End Function
Here it is again, without all the extra comments:
Public Function GetStudentCount(teacher As String) As Integer
Const sql As String = "select COUNT(name) from Info where teacher = ?"
Using con As New OleDbConnection(conn), _
cmd As New OleDbCommand(sql, con)
cmd.Parameters.Add("teacher", OleDbType.VarChar).Value = teacher
con.Open()
Return DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Function
Call it like this:
Private Sub DataGridView1_Click(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Click
lblTeacher.Text = DataGridView1.CurrentRow.Cells("teacher").Value.ToString()
lblCount.Text = GetStudentCount(lblTeacher.Text).ToString()
End Sub