vb.net how to show data from sql in lable - sql

i want show my select syntac into lable but my code no work this only show 1 actualy data is 11
Try
If IsNothing(ds.Tables("kkpsurabaya")) = False Then
ds.Tables("kkpsurabaya").Rows.Clear()
End If
query = "SELECT count(total_telat) FROM kkpsurabaya WHERE LATE <=30 And Late >=1"
da = New SqlDataAdapter(query, conn)
da.Fill(ds, "kkpsurabaya")
Label7.Text = da.Fill(ds, "kkpsurabaya")
da.Dispose()
conn.Close()
Catch ex As Exception
FatalErrorOccured(ex)
End Try

You should not be using a data adapter and DataTable for this. That's for getting a tabular result set. If you want a single value then use a command and call ExecuteScalar.
Dim command As New SqlCommand(query, conn)
Label7.Text = command.ExecuteScalar().ToString()
To learn what ADO.NET objects to use in what situations, check out my examples here.

solved now
conn.Open()
query = "SELECT count(total_telat) as total_telat FROM kkpsurabaya WHERE total_telat <=30 and total_telat >=1"
cmd = New SqlCommand(query, conn)
Try
RD = cmd.ExecuteReader()
If RD.Read() Then
Label7.Text = RD.GetValue(0)
End If
RD.Close()
Catch ex As System.Exception
MsgBox(ex.Message)
End Try
conn.Close()

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

How to refresh GridView's data after update or delete operation in case of , GridControl.datasource = Datatable in Devexpress

I have a devexpress gridview that is related to a table in a sql server database. I am trying to refresh the gridview right after performing a delete but nothing I've tried so far has worked. (I've verified that the delete operation has worked in the table). I've tried 3 ways of updating the gridview but nothing has worked:
GridControl1.Refresh()
GridView1.RefreshData()
GridControl1.RefreshDataSource()
GridView1.RefreshEditor(True)
Here is the complete code of the whole operation:
Using cnn As New SqlConnection(FrmGeneralConfig.GetInstance.getConnection())
Try
cnn.Open()
Dim daDelete As New SqlDataAdapter
Dim command As SqlCommand = New SqlCommand("DELETE FROM Client_Excepte_Charge_Min WHERE ClientNo = #ClientNo", cnn)
command.Parameters.AddWithValue("#ClientNo", clientNo)
daDelete.DeleteCommand = command
daDelete.DeleteCommand.ExecuteNonQuery()
cnn.Close()
Catch ex As Exception
MessageBox.Show("Erreur: " & ex.Message)
Finally
GridControl1.Refresh()
GridView1.RefreshData()
GridView1.RefreshEditor(True)
End Try
End Using
You need to update your DataTable after deleting the rows in server.
Here is example:
Using cnn As New SqlConnection(FrmGeneralConfig.GetInstance.getConnection())
Try
cnn.Open()
Dim command As SqlCommand = New SqlCommand("DELETE FROM Client_Excepte_Charge_Min WHERE ClientNo = #ClientNo", cnn)
command.Parameters.AddWithValue("#ClientNo", clientNo)
command.ExecuteNonQuery()
dtExceptions.Clear()
Using adapter As New SqlDataAdapter()
Dim selectCommand = New SqlCommand("SELECT * FROM Client_Excepte_Charge_Min", cnn)
adapter.SelectCommand = selectCommand
adapter.Fill(dtExceptions)
End Using
cnn.Close()
Catch ex As Exception
MessageBox.Show("Erreur: " & ex.Message)
End Try
End Using

error 'There is already an open DataReader associated with this Command which must be closed first.'

I use below code but it gives error on sentence icount = cmd.ExecuteNonQuery
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Try always calling the Close method when you have finished using the DataReader object.
dr1.Close();
Another optionis to turn on MARS , in your connection string just add "MultipleActiveResultSets=True;"
Try this:
Try
insert data in combobox
cmd.Connection = con
cmd.CommandText = "select name from party"
dr = cmd.ExecuteReader()
cb_ms.Items.Add("---Select---")
cb_ms.SelectedIndex = 0
While dr.Read() 'get error here.'
cb_ms.Items.Add(dr("name"))
End While
dr.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
You could just close the datareader before the 2nd query, but it's better still to get this all into a single query in the first place. Moreover, you really need to close that awful sql injection issue.
Try this to fix both issues:
Dim sql As String = _
"IF NOT EXISTS
(
SELECT 1 FROM [SchoolERP].[dbo].[caste] where (caste = #caste )
)
BEGIN
INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES( #caste)
END"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'Use actual columnn type from the database here
cmd.Parameters.Add("#caste", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cn.Open()
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
End Using
Use Try.. Catch.. Finally... End Try somehing like this:
Try
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Catch error As Exception
........
Finally
dr1.Close
End Try
I got Answer ... i only close connection before icount = cmd.ExecuteNonQuery this sentence and again open connection...and its works..
thanks disha..

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

Binding results of a sql query to listbox

I am getting stuck on this problem. It seems simple but for some reason im having trouble.
Here is what I have of the following:
Try
cn = New OleDbConnection("Provider=microsoft.Jet.OLEDB.4.0;Data Source=G:\Sean\BMSBonder3_0.mdb;")
cn.Open()
str = "Select Distinct BonderIdentifier From [Session]"
cmd = New OleDbCommand(str, cn)
dr = cmd.ExecuteReader
dr.Read()
If dr.Item(0).ToString <> "" Then
ListBox1.Items.Add(dr.Item(0))
End If
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
This works to get only one of the values. Actually the last. how can i get all of them?
Sorry for the newb question. Searching didnt help too much.
You need to use a While loop to repeatedly execute your code until dr.Read() returns False.
For example:
While dr.Read()
If dr.Item(0).ToString <> "" Then
ListBox1.Items.Add(dr.Item(0))
End If
Wend