Fill data grid view from sql table - vb.net

I have four columns in Datagridview. I want to fill first two columns with data from sql database. I try to fill Datagridview. It not display data, but it generate rows.
This is my code:
getConnect()
Try
Conn.Open()
Dim strSQL As String = "SELECT EMP_ID, EMP_NAME FROM EMPLOYEE ORDER BY EMP_NAME ASC"
Conn.Close()
Dim da As New SqlDataAdapter(strSQL, Conn)
Dim dt As New DataTable("EMPLOYEE")
da.Fill(dt)
ATCGRID.DataSource = dt
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
Please check my code and give me solution...

Try this code .
getConnect()
Try
Conn.Open()
Dim strSQL As String = "SELECT EMP_ID, EMP_NAME FROM EMPLOYEE ORDER BY EMP_NAME ASC"
Conn.Close()
Dim da As New SqlDataAdapter(strSQL, Conn)
Dim ds As new Dataset
da.Fill(ds,"EMPLOYEE")
ATCGRID.DataSource = ds.tables(0)
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try

Public Sub OpenConnect()
Try
CmdSql.Connection = conn
conn.Open()
CmdSql.CommandType = CommandType.Text
Catch ex As Exception
' MsgBox(ex.Message)
End Try
End Sub
' this worked perfectly

Thanks for the sub getConnect() it worked perfectly. mine also worked.
Sub RefreshGrid()
' refresh the datagrid
OpenConnect()
CmdSql.CommandText = "SELECT manager_id,manager_name FROM tbl_Manager"
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
dgvMgr.DataSource = ds.Tables(0)
'THIS MODULE WORKED JUST Please Fill Property Columns
'DataPropertyName as Field Database,
'Eg : Column1-DataPropertyName=manager_id and so on.
End Sub

Related

using datagridview for 2 different queries, 1 at a time clearing previous datasource in datagridview

I have multiple queries need to be shown on single Datagridview. Query runs one at a time. The problem is when while running the second query the previous query data columns will still exist and concatenate to new query.
Example Query1: A,B,C,D columns are shown on datagridview
Query2: has E,F,G columns but when I run the Query 2 it shows A,B,C,D,E,F,G.
I need only E,F,G to be displayed. wasnt able to clear the columns
Query1:
With cmd
.Connection = con
.CommandText = "SELECT vouchertype as [Voucher Type], voucherdate as [Voucher Date],VoucherNo as [Voucher No.], Party as [party Name], DISCOUNT,TAX,NETAMOUNT FROM SALESREPORT where vouchertype='Sale' and VOUCHERDATE BETWEEN '" & DATE1.Text & "' AND '" & DATE2.Text & "' "
End With
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
Query2:
With cmd
.Connection = con
.CommandText = "SELECT DESCRIPTION AS [ITEM PARTICULAR], [TYPE] AS [TRANSACTION], REF AS [REFERENCE], QTY AS [QUANTITY], OPENINGBALANCE, OPENINGVALUE, INWARDSQTY,INWARDSVALUE, OUTWARDSQTY,OUTWARDSVALUE FROM STOCK_MOVEMENT WHERE DATES BETWEEN '" & DATE1.Text & "' AND '" & DATE2.Text & "' "
End With
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
Things I Tried:
Try
dt.Columns.Clear()
dt.Rows.Clear()
DataGridView1.DataSource = dt
Catch ex As Exception
End Try
Try
DataGridView1.Rows.Clear()
Catch ex As Exception
End Try
Try
dt.Clear()
Catch ex As Exception
End Try
Try
dTable.Clear()
Catch ex As Exception
End Try
Try
DataGridView1.Columns.Clear()
Catch ex As Exception
End Try
Try
DataGridView1.DataSource = Nothing
Catch ex As Exception
End Try
Try
dt.Clear()
da.Fill(dt)
Catch ex As Exception
End Try
Try
DataGridView1.Rows.Clear()
DataGridView1.Refresh()
Catch ex As Exception
End Try
Try
DataGridView1.DataSource = Nothing
Catch ex As Exception
End Try
Try
ds.Clear()
DataGridView1.Rows.Clear()
Catch ex As Exception
End Try
Create a new DataTable each time rather than reusing an existing one.
DataGridView1.DataSource = Nothing
DataGridView1.Columns.Clear()
DataGridView1.DataSource = dt

vb.net how to show data from sql in lable

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()

Display data from database to textbox

I trying to show the data from database to textbox , that what I write in textbox.
this is my last code I got. here the data showing in to datagrid. instead of datagrid how to get the data to textboxes.
Public Sub SelectItem(ByVal ItemCode As String)
Try
sql.OpenDbConnection()
Dim strSQL As String = "SELECT ItemCode 'Item Code',ItemName 'Item Name' " & _
" FROM tblItemMaster where ItemCode= #ItemCode"
Dim cmd As New SqlCommand(strSQL, sql.SqlConn)
Dim ds As New DataSet
cmd.Parameters.AddWithValue("ItemCode", ItemCode)
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds, "tblItemMaster")
dgvPurchaseOrder.DataSource = ds.Tables("tblItemMaster")
sql.SqlConn.Close()
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
I have no idea how to do that. please help me
If you want to populate textboxes try something like...
Public Sub SelectItem(ByVal ItemCode As String)
Try
sql.OpenDbConnection()
Dim strSQL As String = "SELECT ItemCode [Item Code],ItemName [Item Name] FROM tblItemMaster where ItemCode= #ItemCode"
Dim cmd As New SqlCommand(strSQL, sql.SqlConn)
cmd.Parameters.AddWithValue("ItemCode", ItemCode)
Dim myReader As sqlDataReader
myReader = cmd.ExecuteReader()
If myReader.HasRows Then
myReader.Read()
txtItemCode.Text = myReader.GetValue(0).ToString()
txtItemName.Text = myReader.GetValue(1).ToString()
Else
MessageBox.Show("No data found", "No Data")
End If
myReader.Close()
sql.SqlConn.Close()
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
The below code should return the ItenName, Qty and Price into text boxes named TxtName, txtQty and txtPrice. You don't need a DataSet at all if you want to retrieve a single value.
Public Sub SelectItem(ByVal ItemCode As String)
Try
sql.OpenDbConnection()
Dim strSQL As String = "SELECT ItemName, Qty, Price " & _
"FROM tblItemMaster WHERE ItemCode = #ItemCode"
Dim cmd As New SqlCommand(strSQL, sql.SqlConn)
cmd.Parameters.AddWithValue("#ItemCode", ItemCode)
Dim reader As SqlDataReader
reader = cmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
txtItemName.Text = reader.GetValue(0)
txtQty.Text = reader.GetValue(1).ToString()
txtPrice.Text = reader.GetValue(2).ToString()
reader.Close()
End If
Catch ex As SqlException
MsgBox(ex.Message)
End Try
End Sub

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.

Insert data From DatagridView to Access Database VB.NET

I cannot insert data from DataGridView to Access database. It shows Syntax Error in INSERT INTO Statement. Please help me. This is my code:
Try
com = New OleDb.OleDbCommand
com.Connection = con
Dim atdate As Date
Dim id As String
Dim name As String
Dim time As String
Dim status As String
For x As Integer = 0 To ATCGRID.Rows.Count - 1
atdate = ATCGRID.Rows(x).Cells(2).Value
id = ATCGRID.Rows(x).Cells(0).Value
Name = ATCGRID.Rows(x).Cells(1).Value
time = ATCGRID.Rows(x).Cells(3).Value
status = ATCGRID.Rows(x).Cells(4).Value
con.Open()
str1 = "INSERT INTO EMP_ATTENDANCE(DATE,EMP_ID,EMP_NAME,EMP_TIME,EMP_STATUS)values(#DATE,#EMP_ID,#EMP_NAME,#EMP_TIME,#EMP_STATUS)"
Dim com As New OleDb.OleDbCommand(str1, con)
com.Parameters.AddWithValue("#DATE", atdate)
com.Parameters.AddWithValue("#EMP_ID", id)
com.Parameters.AddWithValue("#EMP_NAME", Name)
com.Parameters.AddWithValue("#EMP_TIME", time)
com.Parameters.AddWithValue("#EMP_STATUS", status)
com.ExecuteNonQuery()
com.Dispose()
Next
con.Close()
MessageBox.Show("Registered Successfully!", "Register", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As OleDb.OleDbException
MsgBox(ex.Message, MsgBoxStyle.Critical, "Oledb Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
"Date" is most likely a keyword. Try placing it in brackets: [DATE] in your SQL text.