How do I filter multiple columns in datagridview exported from excel in VB.NET - vb.net

I have a datagridview which i import an excel file.my excel columns are name,id,sex,grade,seat no .what i want is filter all the columns (multi column filter) in the datagridview except name and id via a textbox. i.e. when i type a single word in the text box i want it to filter the columns of sex,grade and seat no at the same time.
here is the excel importing code to the datagridview....
Private Sub OpenFileDialog1_FileOk(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim filePath As String = OpenFileDialog1.FileName
Dim extension As String =
Path.GetExtension(filePath)
Dim header As String = If(rbHeaderYes.Checked, "YES", "NO")
Dim conStr As String, sheetName As String
conStr = String.Empty
Select Case extension
Case ".xls"
'Excel 97-03
conStr = String.Format(Excel03ConString, filePath, header)
Exit Select
Case ".xlsx"
'Excel 07
conStr = String.Format(Excel07ConString, filePath, header)
Exit Select
End Select
'Get the name of the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
cmd.Connection = con
con.Open()
Dim dtExcelSchema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
sheetName = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
con.Close()
End Using
End Using
'Read Data from the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmd.CommandText = (Convert.ToString("SELECT * From [") & sheetName) + "]"
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
'Populate DataGridView.
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub

You should bind your DataTable to a BindingSource, which you would add in the designer, and then bind that to the grid. You can then filter the data by setting the Filter property of the BindingSource. It's basically a SQL WHERE clause so, just like in SQL, you can use AND and OR operators to combine multiple criteria, e.g.
myBindingSource.Filter = String.Format("Column1 LIKE '%{0}%' OR Column2 LIKE '%{0}%'", myTextBox.Text)
Just note that you can only use LIKE for text columns, not numbers or dates or anything else.

Related

Data not showing up in DataGridView after a search query

Hello i am trying to search for data from a table using a funcion, however when i Input the number of the customerID it doesnt show up in the data gridview but the data is still passed to my textboxes. Could anyone help me in explaining what I did wrong?
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = Fname
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customers")
dt = newds.Tables(0)
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
dgvCustomerInfo.DataSource = dt
con.Close()
End Using
Return dt
End Function
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
If txtSearchName.Text <> "" Then
SearchData(txtSearchName.Text, "0")
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
ElseIf txtSearchID.Text <> "" Then
SearchData("0", txtSearchID.Text)
Dim dt = GetSearchResults(txtSearchID.Text)
dgvCustomerInfo.DataSource = dt
End If
End Sub
Try to think about what each line of code is doing. See in line comments
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
'Delete this line - there is no need for a Dataset
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open() 'Move this line - don't open the connection until directly before the .Execute...
'The Like operator would expect a pattern to match
'The interpolated string with the percent signs add wildcard characters
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
'Delete - We don't need a DataAdapter
Dim da As New SQLiteDataAdapter(cmd)
'Delete - We already have a filled DataTable
da.Fill(newds, "customers")
'Delete - same as above
dt = newds.Tables(0)
'Delete - Have no idea what this does. You are already going to display your data in a grid
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
'Delete - You will set the DataSource in the User Interface code
dgvCustomerInfo.DataSource = dt
'Delete - End Using closes the connection and disposes the connection and command.
con.Close()
End Using
Return dt
End Function
The corrected code will look like this.
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
In the user interface code I have added in line comments.
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
'Declare the DataTable outside the If block
'We do not need a New DataTable because SearchData is returning a DataTable
Dim dt As DataTable
If txtSearchName.Text <> "" Then
'Call only one function to return the DataTable
'SearchData is expecting 2 parameters, a String and an Integer
'Putting 0 in quotes makes it a String
dt = SearchData(txtSearchName.Text, 0)
'I removed the DataSource, Don't repeat yourself
'Assign it once after the If
ElseIf txtSearchID.Text <> "" Then
'The second argument must be an Integer, therefore the CInt()
dt = SearchData("", CInt(txtSearchID.Text))
Else
'Needed to add an Else to assign a value to dt if all else fails
dt = Nothing
End If
dgvCustomerInfo.DataSource = dt
End Sub

Double click datagrid and paste to database record

I want to double click a row in my datagrid and to transfer that data to my database, which then goes on to open a report based on that data just transferred.
If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
Dim selectedRow = DataGridView1.Rows(e.RowIndex)
End If
'Dim PtwNoData As String = String.Empty
Dim connection As SqlConnection
Dim Command As SqlCommand
Dim dt As New DataTable
Dim IdLast As Integer
Dim PTWNo As String
Dim Reader As SqlDataReader
connection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\IzzyM\Desktop\Developer\BIG\Permit Plus\Permit Plus\Database1.mdf;Integrated Security=True")
Dim GuiD As String
'GuiD = Me.DataGridView1.SelectedRows("GUID").Selected.
Try
connection.Open()
Dim Query As String
Query = "insert into PTWData * values ('" & Me.DataGridView1.SelectedRows(). & "')"
Command = New SqlCommand(Query, connection)
Reader = Command.ExecuteReader
connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
'Form4.Dispose()
Dim f As New Form4()
f.TopMost = True
f.Show()
'Form4.Show()
End Sub```
You're wanting to add string values there, but the selected rows is a complicated object. It contains the resulting rows and each column within (along with many, many properties).
See below, where "ColumnNameIDK" is only one and you may have many to consider. This query will ultimately be a lot of inserts. (For safety sake, we may want to convert this to a parameterized query down the road)
...
Dim Query As String
Dim rows As DataGridViewSelectedRowCollection = MyDataGridView.SelectedRows
for each row in Me.DataGridView1.SelectedRows()
Dim myRow As DataRow = (TryCast(row.DataBoundItem, DataRowView)).Row
query &= "insert into PTWData * values ('" & myRow("ColumnNameIDK")& "');"
'this query appended on each pass
next
Command = New SqlCommand(Query, connection)
Reader = Command.ExecuteReader

How to update access db by editing datagridview cells?

Im trying to edit items after inserting to access by clicking the save button? How can i save the edits done in datagridview rows to access?
Already tried the update query
For each loop
vb.net
Private Sub BunifuFlatButton1_Click(sender As Object, e As EventArgs) Handles BunifuFlatButton1.Click
Dim constring As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb")
Dim conn As New OleDbConnection(constring)
For Each row As DataGridViewRow In DataGridView1.Rows
Using con As New OleDbConnection(constring)
'nettxt.Text = (grosstxt.Text * perdistxt.Text / 100) - (dislctxt.Text + disusd.Text + distax.Text)
Dim cmd As New OleDbCommand("Update PurchaseInvoice set [Itemnum] = #ItemNum, [Itemname]= #ItemName, [Itemqty]= #ItemQty, [Itemprice] = #ItemPrice, [discount] =#discount, [subtotal] = #subtotal,[Preference] = " & preftxt.Text & ", [Suppnum] = " & pnumtxt.Text & ", [UniqueID] = " & pautotxt.Text & " Where [UniqueID] = " & pautotxt.Text & "", con)
cmd.Parameters.AddWithValue("#ItemID", row.Cells("ItemID").Value)
cmd.Parameters.AddWithValue("#ItemName", row.Cells("ItemName").Value)
cmd.Parameters.AddWithValue("#ItemQty", row.Cells("ItemQty").Value)
cmd.Parameters.AddWithValue("#ItemPrice", row.Cells("ItemPrice").Value)
cmd.Parameters.AddWithValue("#discount", row.Cells("discount").Value)
cmd.Parameters.AddWithValue("#subtotal", row.Cells("subtotal").Value)
cmd.Parameters.AddWithValue("#Ref", preftxt.Text.ToString)
cmd.Parameters.AddWithValue("#Suppnum", Convert.ToInt32(pnumtxt.Text))
cmd.Parameters.AddWithValue("#UniqueID", Convert.ToInt32(pautotxt.Text))
DataGridView1.AllowUserToAddRows = False
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
'This the code i used to show the data in datagridview:
Private Sub NewPurchaseInvoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb"
con.Open()
Dim sql As String = "Select [Itemnum],[Itemname],[Itemprice],[ItemQty],[discount],[subtotal] from PurchaseInvoice where [UniqueID] = " & pautotxt.Text & ""
Dim cmd10 As OleDbCommand = New OleDbCommand(Sql, con)
'Dim adap As New OleDbDataAdapter("Select [Itemnum],[Itemname],[Itemprice],[discount],[subtotal] from PurchaseInvoice where UniqueID = " & pautotxt.Text & "", con)
'Dim ds As New System.Data.DataSet
'adap.Fill(ds, "PurchaseInvoice")
Dim dr As OleDbDataReader = cmd10.ExecuteReader
Do While dr.Read()
DataGridView1.Rows.Add(dr("ItemNum"), dr("ItemName"), dr("ItemQty"), dr("ItemPrice"), dr("discount"), dr("subtotal"))
Loop
con.Close()
I expect that all the rows will be updated as each other, but the actual output is that each row has different qty name etc...
This code does not seem appropriate in the load event because pautotxt.Text will not have a value yet. Can you move it to a Button.Click?
I guessed that the datatype of ID is an Integer. You must first test if the the .Text property can be converted to an Integer. .TryParse does this. It returns a Boolean and fills IntID that was provided as the second parameter.
You can pass the connection string directly to the constructor of the connection. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. You can pass the Select statement and the connection directly to the constructor of the command.
ALWAYS use Parameters, never concatenate strings to avoid sql injection. Don't use .AddWithValue. 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
The DataAdapter will open the connection, fiil the DataTable and close the connection if it finds it closed; however if it is found open it will leave it open.
The last line binds the grid to the DataTable.
Private Sub FillGrid()
If Not Integer.TryParse(pautotxt.Text, IntID) Then
MessageBox.Show("Please enter a number")
Return
End If
dt = New DataTable()
Using con As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(Sql, con)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Dim adap = New OleDbDataAdapter(cmd)
adap.Fill(dt)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
DataTables are very clever. When bound to a DataGridView they keep track of changes and mark rows as update, insert, or delete. The DataAdapter uses this info to update the database. Once the database is updated we call .AcceptChanges on the DataTable to clear the marking on the rows.
Private Sub UpdateDatabase()
Using cn As New OleDbConnection(ConnString)
Using da As New OleDbDataAdapter(Sql, cn)
da.SelectCommand.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Using builder As New OleDbCommandBuilder(da)
da.Update(dt)
End Using
End Using
End Using
dt.AcceptChanges()
End Sub

Loop through databases get the value and put it in a specific place in datagridview

I have a DataGridView with 2 columns. The first column is populated with folder paths and the second column is empty. Inside each folder path is a single database named DB1. I would like to extract 1 value (VALUE) from each database and then put that value next to corresponding database path, in the second column. This is the query I am using
Select CODE, VALUE from DB1 where CODE = 2419
I know how to populate a DataGridView and how to extract 1 value from the database, but with this I don't even know where to begin.
EDIT
I've managed to create working loop but don't know how to add those values to corresponding places in datagridview.
For Each row As DataGridViewRow In DataGridView1.Rows
Dim sendtroopid As String
sendtroopid = row.Cells("CODE").Value
On Error Resume Next
Dim FilePath As String = sendtroopid 'DATABASE PATH
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT CODE, VALUE FROM DB1 WHERE CODE = #CODE", con)
cmd.Parameters.AddWithValue("#CODE", "2419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
While (reader.Read())
MsgBox(reader("VALUE"))
End While
End Using
End Using
End Using
Next
EDIT 2
With code above I get all values in msgbox. Only thing left is to insert another loop to put all those values (starting with row 0) to datagridview.
If I replace msgbox with
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = (reader("VALUE"))
Next
then all rows are populated with only last value (value from last database).
EDIT 3
I've changed
value = reader.Read()
with
While (reader.Read())
value = reader("VALUE")
End While
I'm still not sure how your query works, but assuming it does, I've changed your code.
For Each row As DataGridViewRow In DataGridView1.Rows
Dim sendtroopid As String
sendtroopid = row.Cells("CODE").Value
On Error Resume Next
Dim FilePath As String = sendtroopid 'DATABASE PATH
Dim value as string = "" ' declare a string variable to hold the result
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT CODE, VALUE FROM DB1 WHERE CODE = #CODE", con)
cmd.Parameters.AddWithValue("#CODE", "2419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
value = reader.Read()
End Using
End Using
End Using
row.Cells(1) = value ' put it in the datagridview cell
Next
Fill it as the rows draw..
Protected Sub GridView1_RowDataBound(sender As Object, e As _
System.Web.UI.WebControls.GridViewRowEventArgs) Handles _
GridView1.RowDataBound
Dim DGRow As GridViewRow = sender
If DGRow.RowType = DataControlRowType.DataRow Then
Dim TestPath As String = DGRow.Cells(0).Text
Dim FoundKey As String = GetKeyFromOtherDatabase(TestPath)
DGRow.Cells(1).Text = FoundKey
End If
End Sub
Private Function GetKeyFromOtherDatabase(testpath) As String
Dim FoundKey As String = ""
' FoundKey = Double something magical...
Return FoundKey
End Function

How to extract data from Access db and place it into a text box using vb.net?

Hi guys I'm trying to search an employee information using SQL from MS Access, and hoping to put the fname lname and such details in their respective textbox which correspond to a specific employee's ID number. I have managed to make the SQL work but I don't know how to extract files from my sql statement and place it inside .text(text box), can you please guide me? Thanks
Here is my code so far:
(UPDATED my code) got an error message : Additional information: ExecuteReader: Connection property has not been initialized. Highlighting Reader below. How can i fix this? I'm trying to extract data and place it into the textbox? Thanks
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Dim path = "Data Source= C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
con.Close()
End Sub
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using da As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = da.ExecuteReader()
If reader.Read() Then
empFnameText.Text = reader("fname")
empLnameText.Text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
for this, you need only this classes: Connection, Command, Reader.
Other classes in the code in question, some are redundant and some are required but in complicated than a simple case presentation.
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.text = reader("fname")
TextBox2.text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
call the method so:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
EDIT - Use parameters:
Private Sub QueryData(PathDb As String, command As String, id As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
com.Parameters.AddWithValue("", id)
connection.Open()
Using reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.Text = reader("fname")
TextBox2.Text = reader("lname")
End If
End Using
connection.Close()
End Using
End Using
End Sub
Call the method:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID = ?"
Dim empNum = "..."
QueryData(path, command, empNum)