if theres no record display in datagridview then messagebox no member found - vb.net

im using datagridview to display employee details and when theres no record found there will be a messagebox that there were no record found here's my code.
Dim search As String = String.Empty
search &= "select * from record "
search &= "where identification=#identification;"
Using conn As New SqlConnection("server=KENJOY_FMCD;database=humanresource;user=ayala747;password=4525422;")
Using cmd As New SqlCommand()
With cmd
.Connection = conn
.CommandType = CommandType.Text
.CommandText = search
.Parameters.AddWithValue("#identification", vsearch.Text)
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
If ds.Tables.Count >= 0 Then
DataGridView1.DataSource = ds.Tables(0)
End If
If (ds Is Nothing) Then
MsgBox("No record found!")
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
End Sub
End Class

Related

No results to select sum to another table with OLEDB in VB.NET

Dear All Master,
I have tried but there is no result from sql select sum and only appears group from the column "PNM". Is there anything wrong with the sql I created?. is there any other solution?.
I don't know why it doesn't appear in the sum value in the "BLC" column in the TEMPTABL table.
Thanks
Private Sub fillDataGridView1()
Try
Dim query As String = "SELECT PNM,NOD,QTY,CIU,DPR FROM GSDTS WHERE QTY > 0"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using da As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
da.Dispose()
source1.DataSource = dt
Me.DataGridView1.DataSource = source1
Me.DataGridView1.Refresh()
End Using
End Using
End Using
Catch ex As Exception
End Try
End Sub
Private Sub fillDataGridView2()
Try
Dim query As String = "select * FROM TEMPTABL"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using da As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
da.Dispose()
source2.DataSource = dt
Me.DataGridView2.DataSource = source2
Me.DataGridView2.Refresh()
End Using
End Using
End Using
Catch ex As Exception
End Try
End Sub
Sub deltemptabl()
Try
Dim sql As String = "DROP TABLE TEMPTABL"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
Catch myerror As Exception
MessageBox.Show("Error: " & myerror.Message)
End Try
End Sub
Sub temptablsum()
Try
'here is the line of code below sql select sum
Dim sql As String = "select PNM, sum((qty*ciu)*(1-dpr/100)) AS BLC INTO TEMPTABL from GSDTS group by PNM"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
Catch myerror As Exception
MessageBox.Show("Error: " & myerror.Message)
End Try
End Sub
DPR is null, therefore it will return null when you try to compute it. You can account for that with isnull(), setting it to 1 (or whatever fits the scenario) whenever the column could be null
sum((qty*ciu)*(1-ISNULL(dpr,1)/100))
Edit:
After looking over it again, you may want to apply the isnull function to the entire sum to return 0 if null. It's difficult to give exacts as I dont know what each column means or specifics to the scenario
ISNULL(sum((qty*ciu)*(1-dpr/100)),0)
Edit/option 2:
Encapsulate that column in a case statement to handle the scenario if needed.
CASE WHEN DPR IS NOT NULL THEN sum((qty*ciu)*(1-dpr/100)) ELSE ReturnSomethingElse END AS DPR
Option 3:
Change the table column and front end to not accept null values if it's not viable for the scenario

the connection string property has not been initialized. vb.net access. BELOW is the code

Try
If MsgBox("SAVE THIS ACADEMIC YEAR?", vbYesNo + vbQuestion, title) = vbYes Then
cn.Open()
cm = New OleDbCommand("update [tblay] set status = 'CLOSE'", cn)
cm.ExecuteNonQuery()
cn.Close()
cn.Open()
cm = New OleDbCommand("INSERT INTO [tblay] (aycode,year1,year2,division)values(#aycode,#year1,#year2,#division)", cn)
With cm
.Parameters.AddWithValue("aycode", txtAY.Text)
.Parameters.AddWithValue("year1", txtYear1.Text)
.Parameters.AddWithValue("year2", txtYear2.Text)
.Parameters.AddWithValue("division", cboDivision.Text)
.ExecuteNonQuery()
End With
cn.Close()
MsgBox("NEW ACADEMIC YEAR HAS BEEN SUCCESSFULLY SAVED!", vbInformation, title)
With frmAY
.LoadRecords()
End With
Clear()
End If
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
This is the code to load records:
Sub LoadRecords()
Try
DataGridView1.Rows.Clear()
Dim i As Integer
cn.Open()
cm = New OleDbCommand("select * from tblay", cn)
dr = cm.ExecuteReader
While dr.Read
i += 1
DataGridView1.Rows.Add(i, dr.Item("aycode").ToString, dr.Item("year1").ToString, dr.Item("year2").ToString, dr.Item("division").ToString, dr.Item("status").ToString)
End While
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
End Sub
This might be more than you want so if so sorry.
SQLite Database (DB) CRUD function are very Boiler Plate Code. That Said I use the same process repetably.
By pacing the code in Using blocks NO need to close the DB and other functions.
I create a button for each function SAVE DELETE and UPDATE that call the function.
Here are the functions.
This code needs to be placed top level
Public connStr As String = "Data Source={0};Version=3;"
Public conn As SQLiteConnection
Here is the SAVE data NOTE the '{gv_dbName} is declared in a Module.
Private Sub InsertSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
Try
cmd.CommandText = "INSERT INTO LinkTable (ytChannelName,ytLinkAddress,ytLastVisit,ytSiteType) VALUES (#ytChannelName,#ytLinkAddress,#ytLastVisit,#ytSiteType)"
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Insert Failed")
End Try
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
Here is the DELETE.
Private Sub DeleteSiteData()
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
cmd.CommandText = "DELETE FROM LinkTable WHERE LID =" & gvID
cmd.ExecuteNonQuery()
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
And the UPDATE.
Public Sub UpdateSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;"),
cmd As New SQLiteCommand("UPDATE LinkTable SET ytChannelName = #ytChannelName, ytLinkAddress = #ytLinkAddress ,ytLastVisit = #ytLastVisit,ytSiteType = #ytSiteType WHERE LID =" & gvID, conn)
conn.Open()
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.Parameters.Add("#LID", DbType.String).Value = gvID
cmd.ExecuteNonQuery()
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub

vb.net Inserting data to access database

I have the following code to input data into my Access database, but I am getting the following error.
Query input must contain at least one table or query.
What am I doing wrong? Here is the section of code that they is mentioning the lines.
Private Sub EditAddButton_Click(sender As Object, e As EventArgs) Handles EditAddButton.Click
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*******************;Jet OLEDB:Database Password=************;")
Dim insertsql As String
Try
insertsql = "INSERT INTO RepairOrders" & _
"(ROOtherInfo, ROJobType, ROJobTime, RODelPicDate, RONo)" & _
"VALUES (#other, #type, #time, #delpic, #jobno) WHERE ROJobNo = #jobno"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#type", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("#time", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("#delpic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#jobno", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have replaced certain information with asterixs' to cover some sensitive information.
EDIT:
Now I am getting a syntax error :(
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*********************************;Jet OLEDB:Database Password=***********;")
Dim insertsql As String
Try
insertsql = "UPDATE RepairOrders SET ROOther = #other, SET RONo = #jobno, SET ROJobType = #type, SET ROJobTime = #time, SET RODelPicDate = #delpic WHERE RONo = #jobno"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#type", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("#time", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("#delpic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#jobno", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
It looks like you have too many SET statements, and OleDb requires '?' for parameters, and you must take care about the amount of them, and the order they are specified. This is a bit cleaned up, take a look at OLEDB Parameterized Query for a more thorough example.
Try
insertsql = "UPDATE RepairOrders
SET ROOther = ?
, RONo = ?
, ROJobType = ?
, SET ROJobTime = ?
, SET RODelPicDate = ?
WHERE RONo = ?"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("?", AddOtherText.Text)
cmd.Parameters.AddWithValue("?", AddJobText.Text)
cmd.Parameters.AddWithValue("?", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("?", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("?", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("?", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

No data available after an Insert operation VB.NET - Windows Forms and Web Service

VB.NET and ASMX Web Service. I am still having the same trouble of getting no data after an insert operation.
Here is my insert code:
Try
'create a MySqlCommand to represent the query
If sqlConn.State = ConnectionState.Closed Then
sqlConn = New MySqlConnection(conStr)
sqlConn.Open()
End If
Dim myCommand As MySqlCommand = New MySqlCommand(strQuery, sqlConn)
If myCommand.ExecuteNonQuery() <> 0 Then
Result = True
End If
Catch ex As Exception
Throw New ApplicationException("Error-luckie's server 2 " & ex.Message)
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
The strQuery will be a simple insert statement.
The code for retrieving data as a dataset is as follows
Public Function ExecuteQuery(ByVal strQuery As String) As DataSet
Dim ds As DataSet = New DataSet 'create a DataSet to hold the results
Try
'create a MySqlCommand to represent the query
If sqlConn.State = ConnectionState.Closed Then
sqlConn = New MySqlConnection(conStr)
sqlConn.Open()
End If
Dim sqlcmd As MySqlCommand = sqlConn.CreateCommand()
sqlcmd.CommandType = CommandType.Text
sqlcmd.CommandText = strQuery
'create a MySqlDataAdapter object
Dim sqlDa As MySqlDataAdapter = New MySqlDataAdapter
sqlDa.SelectCommand = sqlcmd
Try
'fill the DataSet using the DataAdapter
sqlDa.Fill(ds, "Results")
Catch ex As Exception
Throw New ApplicationException("Error-luckie's server 1 " & ex.Message)
End Try
Catch ex As Exception
Throw New ApplicationException("Error-luckie's server 2 " & ex.Message)
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
Return ds
End Function
I am Inserting data from one thread and retrieving data from another (not the same instance of connection is used).
This works perfect if I retrieve data after a 15 minutes gap.
But I want to get the result at once.
Please help.
I would change the method as below
Public Function ExecuteQuery(strQuery As String) As DataSet
Dim ds As New DataSet()
Try
Using con = New MySqlConnection(conStr) 'using statements...
Using cmd = New MySqlCommand(strQuery, con) 'using statements...
Using sqlDa = New MySqlDataAdapter(cmd) 'using statements...
sqlDa.Fill(ds, "Results")
End Using
End Using
End Using
Catch ex As Exception
Throw New ApplicationException("Error-luckie's server 1 " + ex.Message)
End Try
Return ds
End Function
Public Function ExecuteNonQuery(strQuery As String) As Boolean
Try
Using con = New MySqlConnection(conStr) 'using statements...
Using cmd = New MySqlCommand(strQuery, con) 'using statements...
con.Open()
If cmd.ExecuteNonQuery() > 0 Then ' I have change the condition
Return True
End If
End Using
End Using
Catch ex As Exception
Throw New ApplicationException("Error-luckie's server 2 " + ex.Message)
End Try
Return False
End Function

There is already an open DataReader associated with this Connection which must be closed first VB.NET

I get this error message
"There is already an open DataReader associated with this Connection
which must be closed first"
Please help me
My code is:
Public Sub update_qty(ByVal qry1 As String)
Dim dr As MySqlDataReader 'SQLiteDataReader
Dim comm As MySqlCommand 'SQLiteCommand
Try
comm = New MySqlCommand(qry1, conn)
dr = comm.ExecuteReader()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Do While dr.Read()
exe_query("call cargosys.paymentsAdd('" & var1 & "', " & dr("inNo") & ")")
Loop
dr.Close()
End Sub
Public Sub exe_query(ByVal qry As String) As String
Dim cmd As MySqlCommand
Try
cmd = New MySqlCommand(qry, conn)
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MessageBox.Show(ex.ToString)
End Try
End Sub
Your problem is that your code open a DataReader and then execute the SqlCommand when the DataReader read
Try to change this line:
dr = comm.ExecuteReader()
to:
dr = comm.ExecuteReader(CommandBehavior.CloseConnection)
More: DataReader CommandBehavior
Or change your connection string to enable MARS (Multiple Active Result Sets).
This setting will allow for the retrieval of multiple forward-only, read-only result sets on the same connection.
For example :
connectionString=
"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|Northwind.MDF;
Integrated Security=True;
User Instance=True;
MultipleActiveResultSets=True"
More: MARS
EDIT
Since MARS keyword is not supported, try to change your code to this:
Public Sub update_qty(ByVal qry1 As String)
Dim dr As MySqlDataReader 'SQLiteDataReader
Dim comm As MySqlCommand 'SQLiteCommand
Try
comm = New MySqlCommand(qry1, conn)
dr = comm.ExecuteReader()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Dim myList As New List(Of String)
Do While dr.Read()
myList.Add("call cargosys.paymentsAdd('" & var1 & "', " & dr("inNo") & ")")
Loop
dr.Close()
End Sub
Public Sub exe_query(myList As List(Of String))
Dim cmd As MySqlCommand
For Each query As String In myList
Try
cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MessageBox.Show(ex.ToString)
End Try
Next
End Sub
Instead to doing DataReader.Read->SqlCommand.ExecuteNonQuery simultaneously, this code will be read all the data first and then run SqlCommand.ExecuteNonQuery.