Read from database and fill DataTable - vb.net

I'm getting a set of data by a DataReader and assigning to a string. Now I need to fill the DataTable columns with the query fields. The DataTable is connected to a grid to display the filled data.
query is :
strSQL = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee
DataTable columns are EmpCode, EmpID, EmpName.
I need to read the query and assign to the columns of DataTable and fill the table. I have tried as below but i dont get the proper output,
Me.DtShifts.Tables("NonAllocated").Clear()
Me.DtShifts.Tables("NonAllocated").Load(dr)

Connection object is for illustration only. The DataAdapter is the key bit:
Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using

Private Function LoaderData(ByVal strSql As String) As DataTable
Dim cnn As SqlConnection
Dim dad As SqlDataAdapter
Dim dtb As New DataTable
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
dad = New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
cnn.Close()
dad.Dispose()
Catch ex As Exception
cnn.Close()
MsgBox(ex.Message)
End Try
Return dtb
End Function

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

VB.net | how can i turn an access db record in to a tabcontrol add tabpage?

I have a question, I want to add a TabPage to my TabControl from an access record? I think it's something along these lines but it didn't work:
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\data\testing.Accdb;Persist Security Info=False;")
con.Open()
Dim constr As String = "SELECT ProductType, Discription FROM TblProductType"
Dim cmd As OleDbCommand = New OleDbCommand(constr, con)
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
da.Fill(ds, "TblProductType")
Me.TabControl1.TabPages.Add("Discription")
con.Close()
You have to iterate over the row collection of the table:
Using cmd As New OleDbCommand("SELECT ProductType, Discription FROM TblProductType", con)
Using rdr As OleDbDataReader = cmd.ExecuteReader
While rdr.Read
TabControl1.TabPages.Add(rdr("Discription").ToString)
End While
End Using
End Using
Of course, this only gives you an empty TabPage for every record and in it's current implementation, you don't have any reference to the record anymore. That ProductType, if it's unique, should be used somewhere, too.

How to display total sum from database to textboxes?

Guys How can I display the sum from database to textbox1 and textbox2?
Private Sub totalquiz()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
sSQL = "Select sum(quiz) as score,sum(total) as total FROM prelimquiz where [username]='ad' And studentID='1111111'"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
textbox1.Text =dt.Rows[2].ToString()
textbox2.text =dt.rows[3].ToString()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I dont know how to correctly get the total sum and display to textboxes.
your query will return only one record containing the sum you wanted
to access it simply do the following
dt.Rows[0]["score"].ToString();
dt.Rows[0]["total"].ToString();
hope it will help you
regards

Sql Adapter . How to update a DataTable with no primary keys

This table that I have has been created with no primary keys. There is a reason why its been created with no keys. It is something like a product and customer relationship table. So after the standard procedure of using SqlDataAdapter and DataSet along with DataTable to fill the DataGrid I have an error updating the changes.
I have been working on several forms using DataGrid' but they all work fine due to the fact the table have primary keys. I tried adding a composite key but it didn't work. So below is my code for theDataSet` and the update code which works for other forms.
The update codes:
cmdbuilder = New SqlCommandBuilder(adapter)
If primaryDS IsNot Nothing Then
primaryDS.GetChanges()
'update changes
adapter.Update(primaryDS)
MsgBox("Changes Done")
'refresh the grid
CMDrefresh()
End If
And here is the coding for the DataTable I tried adding 5 composite keys. So how do you update with this problem?
Try
myconnection = New SqlConnection(strConnection)
myconnection.Open()
adapter = New SqlDataAdapter(StrQuery, myconnection)
adoPrimaryRS = New DataSet
adapter.Fill(primaryDS)
Dim mainTable As DataTable = primaryDS.Tables(0)
DataGrid.AutoGenerateColumns = False
mainTable.PrimaryKey = New DataColumn() {mainTable.Columns(0), _
mainTable.Columns(1), _
mainTable.Columns(2), _
mainTable.Columns(3), _
mainTable.Columns(4)}
bndSrc.DataSource = mainTable
DataGrid.DataSource = bndSrc
gDB.Connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
So I decided to go on and answer my question. You cant use the code above to up but you can still insert the new rows. Since Dataset is a memory if the whole database was removed it would not be effect. So the answer to how to update a table with no primary key or composite keys it to trancute it then insert all rows from the Dataset Table in to it. Here is the Code for Trancute and The one below is to insert. With these the table gets new values. It works for me.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = strConnection
Dim strSql As String
'MsgBox(con.ConnectionString.ToString)
Try
con.Open()
cmd = New SqlCommand
cmd.Connection = con
strSql = "TRUNCATE TABLE Table1"
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
So here is The Insert code.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim strSql As String
con.ConnectionString = strConnection
For i As Integer = 0 To grdDataGrid.Rows.Count - 1
'MsgBox(con.ConnectionString.ToString)
con.Open()
cmd = New SqlCommand
cmd.Connection = con
Try
strSql = "INSERT INTO Table1 ( [one], [two], [three], [four], [five] )" +_
"VALUES (#one, #two, #three ,#four ,#five )"
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("#one", grdDataGrid.Rows(i).Cells(2).Value)
cmd.Parameters.AddWithValue("#two", grdDataGrid.Rows(i).Cells(0).Value)
cmd.Parameters.AddWithValue("#three", grdDataGrid.Rows(i).Cells(1).Value)
cmd.Parameters.AddWithValue("#four", grdDataGrid.Rows(i).Cells(3).Value)
cmd.Parameters.AddWithValue("#five", grdDataGrid.Rows(i).Cells(4).Value)
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
CMDrefresh()

VB | Loading SQL Query into Combobox

I am trying to fill a combobox with a SQL Result
I think my problem is handling the data in the datatable form.
Dim sql As String
Dim sqlquery As String
Dim ConnectionString As String
ConnectionString = "Data Source=(local);Initial Catalog=Control;Persist Security Info=True;User ID=user;Password=pass"
sqlquery = "Select dbName from Databases"
Using connection As SqlConnection = New SqlConnection(ConnectionString)
connection.Open()
Using conn As SqlCommand = New SqlCommand(sqlquery, conn)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(cmboxDatabaseName)
End Using 'comm
End Using 'conn
When I run the program I just stare at a sad empty combobox.
Almost right, but you need to Load the datatable using the DataReader.
Then assing the DataTable to the DataSource of the Combo
Using connection As SqlConnection = New SqlConnection(ConnectionString)
connection.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, connection)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rs)
' as an example set the ValueMember and DisplayMember'
' to two columns of the returned table'
cmboxDatabaseName.ValueMember = "IDCustomer"
cmboxDatabaseName.DisplayMember = "Name"
cmboxDatabaseName.DataSource = dt
End Using 'comm
End Using 'conn
Also you could set the combobox ValueMember property to the name of the column that you will use as key for future processing and the DisplayMember property to the column name that you want to display as text to choose from for your user
you can also do it as
Dim Con = New SqlConnection(_ConnectionString)
Dim cmdAs New SqlCommand
Dim dr As New SqlDataReader
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.