Data not showing up in DataGridView after a search query - vb.net

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

Related

How to call the datatable fill code without double in vb.net

How to call the datatable fill code without double in vb.net?.
in the code below you might see I wrote back the fill datatable code if there is a solution without me writing it back in "GenerateReport()". Please Recommend.
Thanks
Private WithEvents dt As New DataTable
Public Sub fillDataGridView1()
dt = New DataTable
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Me.grid.DataSource = dt
Me.grid.Refresh()
End Using
End Using
End Using
End Sub
Private Sub GenerateReport()
KtReport1.Clear()
'the code below actually already exists but I reuse it
dt = New DataTable
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
Dim dtCloned As DataTable = dt.Clone()
dtCloned.Columns("CIA").DataType = GetType(String)
For Each row As DataRow In dt.Rows
dtCloned.ImportRow(row)
Next row
KtReport1.AddDataTable(dtCloned)
The issue is that you are essentially duplicating code despite the fact that you have a variable setup to hold the filled DataTable at the Form level.
What I would suggest doing is creating a function that returns the filled DataTable, then at the top of your two existing methods do a null check against the Form level variable.
Take a look at this example:
Private _dt As DataTable
Private Function GetAndFillDataTable() As DataTable
Dim dt As New DataTable()
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Return dt
End Using
End Using
End Using
End Function
Private Sub FillDataGridView1()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
grid.DataSource = _dt
grid.Refresh()
End Sub
Private Sub GenerateReport()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
Dim dtCloned As DataTable = _dt.Clone()
dtCloned.Columns("CIA").DataType = GetType(String)
For Each row In _dt.Rows
dtCloned.ImportRow(row)
Next row
KtReport1.AddDataTable(dtCloned)
End Sub

Update edited ComboBox items in database instead of adding them

I have a combobox named "Barcode", I fill it from database like this:
Sub fillIBarcode()
Barcode.DataSource = Nothing
Barcode.Items.Clear()
Dim adp As New SqlClient.SqlDataAdapter("Select distinct Barcode from Items where ItemCode=N'" & (ItemsDGV.CurrentRow.Cells(0).Value) & "'", SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
'=====================================================
For I = 0 To dt.Rows.Count - 1
Barcode.Items.Add(dt.Rows(I).Item("Barcode"))
Barcode.SelectedIndex = 0
Next
End Sub
And it displays like that:
When the user edits and changes any numbers in the combobox and clicks the "Edit" button, how to submit this change and update the combobox items list immediately in the database?
I tried:
Private Sub Editbtn_Click(sender As Object, e As EventArgs) Handles Editbtn.Click
Dim cmdd As New SqlClient.SqlCommand
cmdd.Connection = SQlconn
cmdd.CommandText = "delete from Items where ItemCode=N'" & (ItemCode.Text) & "'"
cmdd.ExecuteNonQuery()
Dim sql = "select * From Items where ItemCode=N'" & (ItemCode.Text) & "'"
Dim adp As New SqlClient.SqlDataAdapter(sql, SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
If dt.Rows.Count = 0 Then
For i = 0 To Barcode.Items.Count - 1
Dim dr = dt.NewRow
dr!ItemCode = ItemCode.Text
dr!Barcode = Barcode.Items(i).ToString
dt.Rows.Add(dr)
Next
Dim cmd As New SqlClient.SqlCommandBuilder(adp)
adp.Update(dt)
End If
End Sub
But it adds the new value, instead of updating the existing one.
I mean it added three barcodes, the original two, and the new edited one.
use SQL UPDATE QUERY :
you must conserve dt across form event to keep old value
dt has same index as combobox
declare dt as global in front of form code
Dim dt as datatable
in Sub fillIBarcode() remove DIM
dt = ds.Tables(0)
and in event handler execute an UPDATE query with ref to combobox selectedIndex:
Private Sub Editbtn_Click(sender As Object, e As EventArgs) Handles Editbtn.Click
Dim cmdd As New SqlClient.SqlCommand
cmdd.Connection = SQlconn
cmdd.CommandText = "UPDATE Items SET ItemCode=N'" & (ItemCode.Text) & "' WHERE ItemCode = N'" & dt.rows(Barcode.SelectedIndex).Item("Barcode") & "'"
cmdd.ExecuteNonQuery()
'update dt
dt.rows(Barcode.SelectedIndex).Item("Barcode") = ItemCode.Text
End Sub

i have change the background color of row in datagridview if already expired the medicine?

i have change the background color of row in datagridview if already expired the medicine?
con.Open()
Dim query As String
query = "Select product_code,drug_name,quantity,expiration_date from medicine where expiration_date"
command = New MySqlCommand(query, con)
readers = command.ExecuteReader
Dim count As Integer
count = 0
While readers.Read
count = count + 1
End While
con.Close()
If count = 0 Then
MsgBox("no expiration")
Else
Dim SQL As String = ""
Dim da As MySqlDataAdapter = Nothing
Dim dt As New DataTable
SQL = "Select product_code,drug_name,quantity,expiration_date from medicine where expiration_date"
command = New MySqlCommand(SQL, con)
End If
Ok fist of all you need to load de grid with the database data in this way:
con.Open()
Dim query As String
Dim da As new MySqlDataAdapter
Dim dt As New DataTable
query = "Select product_code,drug_name,quantity,expiration_date from medicine where expiration_date is not null"
command = New MySqlCommand(query, con)
da.SelectCommand = cm
da.Fill(dt)
dgv1.datasource = dt
Then you have to set the color in the cellformating event:
Private Sub dgv1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgv1.CellFormatting
If dgv1.Rows(e.RowIndex).Cells("expiration_date").Value < now Then
dgv1.Rows(e.RowIndex).cells("expiration_date").Style.BackColor = Color.Red
End If
I do not understand what you are trying to do or how you are going to load the grid. any way to change the color of a column all you have to do is:
dgv1.Columns("columnsName").DefaultCellStyle.BackColor = Color.Red

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)

need to get value from sql query

Through ADO,I like to do the following query:
select name, address, zip from terr where id = '33334'
I like then to assign name, addess, zip to variables so that I can assign it later in my program.
How do I do this with VB.NET ADO?
Try somethign like this:
Dim dbName As String
Dim dbAddress As String
Dim dbZip As String
Using connObj As New SqlClient.SqlConnection("<connectionString>")
Using cmdObj As New SqlClient.SqlCommand("select name, address, zip from terr where id = '33334'", connObj)
connObj.Open()
Using readerObj As SqlClient.SqlDataReader = cmdObj.ExecuteReader
'This will loop through all returned records
While readerObj.Read
dbName = readerObj("name").ToString
dbAddress = readerObj("address").ToString
dbZip = readerObj("zip").ToString
'handle returned value before next loop here
End While
End Using
connObj.Close()
End Using
End Using
Also, you should look into parameterizing the value for the where clause.
You need a DataBase (i assume MS Sql-Server), a Connection and a DataAdapter to fill a DataTable. Then you have all you need. Here's an example:
Public Function GetUser(UserId As Int32) As DataRow
Using con = New SqlConnection(My.Settings.RM2ConnectionString)
Using cmd = New SqlCommand("select name, address, zip from terr where id = #id", con)
cmd.Parameters.AddWithValue("#id", UserId)
Dim da = New SqlDataAdapter(cmd)
Dim tblUser = New DataTable
da.Fill(tblUser)
If tblUser.Rows.Count <> 0 Then
Return tblUser(0)
Else
Return Nothing
End If
End Using
End Using
End Function
execute a SqlCommand from SQLDatareader, like:
Dim vVendedor As New SqlCommand("SELECT user FROM users", mConeccion)
vDatosVen = vVendedor.ExecuteReader
vVendedor = Nothing
and to get te value:
While vDatosVen.Read()
vUser = vDatosVen("user")
End While
Here's what i did...
Private Sub btn_Connect_Click(sender As Object, e As EventArgs) Handles btn_Connect.Click
Dim sql_connection As New MySqlConnection
Dim sql_query As New MySqlCommand
Dim sql_result As MySqlDataReader
sql_connection.ConnectionString = "Server=localhost;Database=hidden;Uid=root;Pwd=;"
sql_query.Connection = sql_connection
sql_connection.Open()
sql_query.CommandText = "SELECT Entry,name FROM table WHERE entry=1;"
sql_result = sql_query.ExecuteReader
If sql_result.HasRows Then
Do While sql_result.Read()
Dim query_result As String
query_result = sql_result("name")
MsgBox(query_result)
Loop
Else
MsgBox("No results found.")
End If