hangs on datagridview .fill large amount of data - vb.net

Hello I am trying to fill a datagridview with items from a datafile. The code stops on the .fill . I tested the query in excel (Microsoft query) it works fine there. I also tested it (in my vb code) by adding a WHERE to only receive on specific entry, this works fine. Any ideas how to get this to work in my application? Code is below thanks for the help!
Dim dataAdapter As New Odbc.OdbcDataAdapter()
Private Sub ChangeSelect()
Dim selectCommand As String = "SELECT CWIPH.CUST_NO, CWIPH.JOB_NO, CWIPH.JOB_NAME, CJCMS.JOB_DESC FROM { OJ CWIPH CWIPH INNER JOIN CJCMS CJCMS ON CWIPH.JOB_NO = CJCMS.JOB_NO }"
accessDB(selectCommand)
End Sub
Private Sub accessDB(ByVal selectCommand As String)
Dim JobConnectionString As String = "Dsn=Jake; provider=System.Data.Odbc"
Dim cn As OdbcConnection = New OdbcConnection(JobConnectionString)
Dim table As New DataTable()
cn.Open()
Dim cmd As New Odbc.OdbcCommand(selectCommand, cn)
Me.dataAdapter = New Odbc.OdbcDataAdapter(cmd)
With dgvWorkOrder
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New Odbc.OdbcCommandBuilder(Me.dataAdapter)
Me.dataAdapter.Fill(table)
Me.dgvWorkOrder.DataSource = table
cn.Close()
End Sub

This article helped a lot. What's better: DataSet or DataReader?
So I ended up changing my code to use data reader and so far so good.

Related

VB.NET Updating database table using dataset

I am trying to update my physical database using a dataset. There is no error that appears but the Table in my Database doesn't updating at all.
I am using VS 2012, VB.NET
This is my code for updating my database table name "ProdRec"
grid()
Dim da As New OleDbDataAdapter
Dim cb As New OleDb.OleDbCommandBuilder(da)
da.Update(ds, "ProdRec")
ds.AcceptChanges()
I declare my dataset named "ds" in this Public sub
Public Sub grid()
connect()
MD = "Select * From ProdRec"
com = New OleDbCommand(MD, conn)
adaptr = New OleDbDataAdapter(com)
ds = New DataSet
adaptr.Fill(ds, "ProdRec")
With DataGridView1()
.DataSource = ds
.DataMember = "ProdRec"
End With
End Sub
Try to add this before da.Update command: da.UpdateCommand = cb.GetUpdateCommand()

datagridview not updating automatically in vb.net

The datagirdview is not updating after immediate in inserting records.
Private Sub updatedgv()
Using congv As OleDbConnection = New OleDbConnection("Provider=microsoft.jet.oledb.4.0;data source=..\library.mdb")
Dim strgv As String = "select * from NormalTransaction where RegNo='" & txt_RegisterNo.Text & "'"
Dim cmdgv As OleDbCommand = New OleDbCommand(strgv, congv)
Dim sdagv As OleDbDataAdapter = New OleDbDataAdapter(cmdgv)
Dim dsgv As DataSet = New DataSet("gvSet")
sdagv.Fill(dsgv)
DataGridView1.DataSource = dsgv
DataGridView1.DataMember = dsgv.Tables(0).TableName
End Using
End Sub
please help me to solve this.

Database not updating new row

Insert new row inside DataGridView
This answer makes it seem like the database should update with the rows.add
Some other sites have instructions, but form a perspective of creating the database from scratch. I already have a database and just want the stupid thing to accept new data.
Here's what I have done:
Private Sub InitializeDataGridView()
Try
' Set up the DataGridView.
With Me.DataGridView1
' Automatically generate the DataGridView columns.
.AutoGenerateColumns = True
' Set up the data source.
'bindingSource1.DataSource = GetData("SELECT * FROM Places and Stuff")
MyTable = GetData("SELECT * FROM Places and Stuff")
'MyDataSet = bindingSource1.DataSource
'MyTable = MyDataSet.Tables(0)
.DataSource = MyTable
' Automatically resize the visible rows.
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
' Set the DataGridView control's border.
.BorderStyle = BorderStyle.Fixed3D
' Put the cells in edit mode when user enters them.
.EditMode = DataGridViewEditMode.EditOnEnter
' Disables Add New Row
.AllowUserToAddRows = False
End With
Catch ex As SqlException
MessageBox.Show(ex.ToString, _
"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
System.Threading.Thread.CurrentThread.Abort()
End Try
End Sub
I am binding the DGV to a table. It seems like maybe I need a dataset somewhere to update but I cannot figure out how to populate a dataset with a table that is also a sql database. You can also see where I have played around with other datasets/datatables etc.
I also got my datagridview to add a row but the database is being lazy:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Determine Last Row Index
Dim dgvrowCnt As Integer = DataGridView1.Rows.Count - 1
If DataGridView1.Rows.Count > 0 Then
Dim myRow As DataRow = MyTable.NewRow
myRow(0) = DataGridView1.Rows(dgvrowCnt).Cells(0).Value + 1
MyTable.Rows.Add(myRow)
Else
Dim myRow As DataRow = MyTable.NewRow
myRow(0) = 230
MyTable.Rows.Add(myRow)
End If
End Sub
I am a little saddened by not being able to use myRow("<column name here>") = 230 but I'll have to get over it I guess.
I have tried refreshing and checking the table to see if my form needs to be refreshed, but that doesn't seem to be the case.
This page http://support.microsoft.com/kb/301248 has 2 lines and claims it does what I am hoping for:
Dim objCommandBuilder As New SwlCammandBuilder(daAuthors)
daAuthors.Update(dsPubs, "Authors")
I cannot get my table into a dataset as shown in the binding lines of my example.
It seems that you haven't understood a fundamental concept of ADO.NET. The DataTable and other objects like the DataSet are 'disconnected' objects, meaning that adding/updating and removing rows doesn't update/insert/delete the database table.
You need to create an SqlCommand, prepare its command text and then Execute a query to update your db (other methods include using an SqlDataAdapter and its Update method)
For example, to insert a single row in a datatable your code should be something like this
Using con = New SqlConnection(.....constringhere...)
Using cmd = new SqlCommand("INSERT INTO table1 (field1) values (#valueForField)", con)
con.Open()
cmd.Parameters.AddWithValue("#valueForField", newValue)
cmd.ExecuteNonQuery()
End Using
End Using
A more complete tutorial could be found here
Instead this could be a pseudocode to use a SqlDataAdapter and a SqlCommandBuilder to automate the construction of the commands required to store your changes back to the database
' Keep the dataset and the adapter at the global class level'
Dim da As SqlDataAdapter = Nothing
Dim ds As DataSet
Private Function GetData(ByVal sqlCommand As String) As DataSet
ds As New DataSet()
Dim connectionString As String = "Data Source=...."
Using con = New SqlConnection(connectionString)
conn.Open()
Using command = New SqlCommand(sqlCommand, con)
Using da = New SqlDataAdapter(command)
da.Fill(ds)
End Using
End Using
End Using
Return ds
End Function
Use the first table inside the DataSet returned by GetData as Datasource of the grid (or just use the whole dataset)
.DataSource = GetData(.......).Tables(0)
' Add a new button to submit changes back to the database'
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim builder = New SqlCommandBuilder(da)
da.UpdateCommand = builder.GetUpdateCommand()
da.InsertCommand = builder.GetInsertCommand()
da.DeleteCommand = builder.GetDeleteCommand()
da.Update(ds)
End Sub
Please, note that I cannot test this code, and I offer it as a pseudocode without any error checking required by a more robust application.

Saving record with dataset

I want to save a record in the database using a dataset, but my data is not committing into my database.
My code can be viewed below:
Dim mydataset1 As New MyDataSet
Dim row As DataRow = mydataset1.Tables("testtable").NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
mydataset1.Tables("testtable").Rows.Add(row)
Any help will be appreciated
A DataSet/DataTable is a offline/in-memory representation of your database. If you want to update the database, you need to use a DataAdapter.
For example (assuming you're using MS-Sql-Server):
Public Function UpdateDataSet(dataSet As DataSet) As Int32
Using con = New SqlConnection(My.Settings.SqlConnection)
Dim sql = "INSERT INTO TUser(Name,Address)VALUES(#Name,#Address)"
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
cmd.Parameters.Add(New SqlParameter("#Address", SqlDbType.VarChar))
Using da = New SqlDataAdapter()
da.InsertCommand = cmd
con.Open()
Dim rowCount = da.Update(dataSet)
Return rowCount
End Using
End Using
End Using
End Function
I could be rusty here since its a long time since I wrote any VB.NET or used data adapters/datasets/datatables but I think if you decide to take that route you would need code like this:
Dim connection As New SqlConnection("#####YourConnectionString#####")
connection.Open()
Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)
' For the line below to work, you must have a primary key field in "testtable"
Dim builder As New SqlCommandBuilder(adapter)
Dim testtable As New DataTable("testtable")
adapter.Fill(testtable)
Dim row As DataRow = testtable.NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
testtable.Rows.Add(row)
adapter.Update(testtable)
connection.Close()

Windows Forms App: System.NullReferenceException Error

Good day,
I have been trying to figure out the source of error in my application. What this function (GetConcentrations()) is to display data from my database onto a DataGridView. The function is called in the PageLoad but works fine but when I call it in another Sub, I get this error.
Could anyone help me? I already tried different ways.
Thanks!
Here is the code:
Private Sub GetConcentrations()
Dim conString As String = ConfigurationManager.ConnectionStrings("dbAsthmaConnectionString").ConnectionString
Me.dataAdapter = New SqlDataAdapter("Select * from tblConcentrations", conString)
'Dim adapter As New SqlDataAdapter("Select * from tblConcentrations", conString)
Dim dataset As New Data.DataSet
Try
Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
'Dim datasetgetconcentrations = New DataSet
Me.dataAdapter.Fill(dataset)
Me.bindingSource1.DataSource = table
DataGridView3.AutoResizeColumns(DataGridViewAutoSizeColumnMode.AllCellsExceptHeader)
DataGridView3.DataSource = dataset.Tables(0)
dataset.Dispose()
Catch ex As Exception
MsgBox("Failed to display the concentration table (GetConcentrations)!", MsgBoxStyle.Information)
End Try
'Dim ConcentrationValue As Double = DataGridView2.Rows.Contains
'TextBoxCurrentConcentration.Text = txtMessage.Text
End Sub
I don't understand why you call the Fill method two times.
Once to fill a DataTable and one again to fill a DataSet. Only the one for the dataset is really needed.
Could you try if this changes something in your problem?
Dim ds as New DataSet
ds.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(ds)
DataGridView3.AutoResizeColumns(DataGridViewAutoSizeColumnMode.AllCellsExceptHeader)
DataGridView3.DataSource = ds.Tables(0)
Also, don't dispose your dataset on exiting, you are still using it.
In this case it's better to let the Garbage Collection handle this task.