Differences in populate a DataGridView using SQLiteDataAdapter vs. SQLiteDataReader - vb.net

For populate a DataGridView with data from a SQLite DataBase I think the easy way is using SQLiteDataAdapter, populate a Table and make the Table the DataSource of the DataGridView, something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles cdmDataTable.Click
Dim conn = New SQLiteConnection("Data Source=MyDataBase.sqlite;Version=3")
Try
Using (conn)
conn.Open()
Dim sql = "SELECT * FROM users"
Dim cmdDataGrid As SQLiteCommand = New SQLiteCommand(sql, conn)
Dim da As New SQLiteDataAdapter
da.SelectCommand = cmdDataGrid
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
Dim readerDataGrid As SQLiteDataReader = cmdDataGrid.ExecuteReader()
End Using
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Is there any advantage using SQLiteDataReader instead of SQLiteDataAdapter?

Data adapter is a higher level component that connects a DataTable to the underlying database. It can fill the DataTable and it can sync the changes on the DataTable back to the database. The DataAdapter uses a DataReader internally to read the data from the table.
There is no significant advantage using a DataReader over a DataAdapter to fill a DataTable.

Related

Refresh DataGridView vb.net

I have DataGridView which doesn't refresh. I was hoping to be able to refresh it by clicking on the 'Refresh' button.
My database is called 'ProjectDatabase' and the table I want to use is called 'SWOT'.
I'v tried a few ways but none have been working, and if it does work then I get new issues like every time I click on refresh it duplicates the data. Im using a MS Acess Database.
I tried the below coding, it refreshes, but duplicates the data x2 every time I click Refresh:
Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
Refreshdata()
End Sub
Dim myConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\ahmed\OneDrive\Desktop\ProjectDatabase2003.mdb")
Dim DS As DataSet = New DataSet
Dim DA As OleDbDataAdapter
Dim tables As DataTableCollection = DS.Tables
Dim source1 As New BindingSource()
Private Sub Refreshdata()
DA = New OleDbDataAdapter("Select * from SWOT", myConnection)
DA.Fill(DS, "SWOT_Report")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
End Sub
I think that you are overcomplicating your code with the use of the BindingSource, DataSet, DataAdapter, and DataTable member (class scope) variables.
For the member variables, strip them down to these two:
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\ahmed\OneDrive\Desktop\ProjectDatabase2003.mdb"
Dim swotBindingSource As BindingSource
Please note, the myConnection object has been removed and replaced with a Connection String variable instead
In the Forms New() method add:
swotBindingSource = New BindingSource()
DataGridView1.DataSource = swotBindingSource
This will setup your DataGridView to have the swotBindingSource as its DataSource. The BindingSource can be of use later on when it comes to filtering data.
And, finally change the RefreshData sub to be:
Private Sub Refreshdata()
Dim swotDataTable As New DataTable
Using conn As New OleDbConnection(ConnectionString)
Using DA As New OleDbDataAdapter("SELECT * FROM SWOT", conn)
Dim ds As New DataSet
DA.Fill(ds, "SWOT_Report")
swotBindingSource.DataSource = ds.Tables(0)
End Using
End Using
End Sub
When the swotBindingSource gets updated, you should automatically see the updates in the DataGridView.
It is likely you will also have to make other changes to the rest of your code due to the lack of myConnection object, you will be better off creating a new Connection object (similar to how it is done in the RefreshData sub) each time you need to use the database rather than creating one when the application starts and re-using the same connection.
What you need to do is clear your DataTable before filling it again. .NET doesn't do that automatically.
Private Sub Refreshdata()
'-- clear table before filling
If DS.Tables("SWOT_Report") IsNot Nothing Then DS.Tables("SWOT_Report").Rows.Clear
DA = New OleDbDataAdapter("Select * from SWOT", myConnection)
DA.Fill(DS, "SWOT_Report")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
End Sub

textbox AutoComplete not working after a search query

Hello there I am quite new to windows form programming, and my project requires me to do a search query on my database. I would like the option for the names that can be currently searched to be displayed when typing, however, after pressing the search button the autocomplete no longer displays when I try to look for another attribute. https://i.stack.imgur.com/Wytdy.png , https://i.stack.imgur.com/Qjy5q.png
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
MaxRows = ds.Tables("customers").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customers;"
dgvCustomerInfo.DataSource = display(msSQL, "customers")
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT DISTINCT fname FROM customers"
End With
da.SelectCommand = cmd
da.Fill(dt)
Dim r As DataRow
txtSearchName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
txtSearchName.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
I believe your problems stem from the AutoCompleteMode. Suggest and SuggestAppend seem to fill in the text box as expected. Append seem to do nothing. I don't think this is working as intended.
I tested with a little database I have. It is Sql Server but should work the same for Sqlite. I used a bit of Linq magic to get the AutoCompleteCustomSource. A few other changes... Using...End Using blocks ensure that database objects are closed and disposed. You don't need a DataAdapter, just a DataTable and Command.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataForTextBox()
Dim strArray = dt.AsEnumerable().[Select](Function(x) x.Field(Of String)("Name")).ToArray()
TextBox5.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim MySource As New AutoCompleteStringCollection()
MySource.AddRange(strArray)
TextBox5.AutoCompleteCustomSource = MySource
TextBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End Sub
Private Function GetDataForTextBox() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Distinct Name From Coffees", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetSearchResults(TextBox5.Text)
DataGridView1.DataSource = dt
End Sub
Private Function GetSearchResults(name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select * From Coffees Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

The SelectCommand property has not been initialized before calling 'Fill' problem

The SelectCommand property has not been initialized before calling 'Fill' problem:
Private Sub DeleteButton_Click(sender As Object, e As EventArgs) Handles DeleteButton.Click
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim row As New Integer
Try
ds = New DataSet
tables = (ds.Tables)
da = New OleDbDataAdapter
da.Fill(ds, "Booking")
Dim cmdstr As String = "delete * from [Booking] where ID = " & DataGridView1.SelectedRows(0).Cells(0).Value.ToString()
Dim cmd As New OleDbCommand(cmdstr, objCon)
da.SelectCommand = cmd
objCon.Open()
cmd.ExecuteNonQuery()
objCon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Change
da.SelectCommand = cmd
With
da.DeleteCommand = cmd
Reguarding the Dim statements at the beginning of your code; you never use tables, source1 or row in your code so, there is no point in declaring them.
On to the Try You assign a New DataSet to ds. This is empty so assigned the Tables collection to tables makes no sense. This will be empty also.
Next you create a New DataAdapter. A new DataAdapter has no select command so it will be unable to .Fill anything.
Then you assign a Delete command to the SelectCommand property of a DataAdapter. This makes no sense.
Finally you execute you command. This should work if wasn't for the other code.
Keep you Database objects local so you can control their closing and disposing. Using...End Using takes care of this for you. The Using also acts as a Dim statement so it also declares you variables. You can include more than one variable with a single Using by separating them by a comma.
I guessed at the datatype of you ID field. Check your database.
Private Sub DeleteButton_Click(sender As Object, e As EventArgs) Handles DeleteButton.Click
Try
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("delete * from [Booking] where ID = #ID", cn)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = DataGridView1.SelectedRows(0).Cells(0).Value
cn.Open()
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Cannot Add new row to database with DataAdapter.insertCommand vb.net

I try to add new record to the database with command DataAdapter.InsertCommand. But I don't know why It doesn't insert new record to database
Here is my code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\1_Project\Project_of_VB_Net\AccessDatabase\StudentDatabase.accdb"
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO StudentData(StudentID) VALUES (#studentid)"
cmd.Parameters.AddWithValue("#studentid", "123")
Try
cnn.Open()
da.InsertCommand = cmd
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
cnn.Close()
End Try
End Sub
Please help me find out what's wrong with it?
I'm all in favor of using what works and I see the solution above works. The advantage of using a dataadapter however, is that it wraps all the sql commands needed for the CRUD operations of the datatable. You can configure your own commands or let visual studio configure them automatically by using a sqlcommandbuilder. Then once you have the adapter configured all you need to do is something like this
Dim myds As New DataSet()
Dim mytable as New datatable()
myds.Tables.Add(mytable)
Dim myconstr As String = "ConnectionStringtoDataBase"
Dim myconn As New SqlConnection(myconstr)
Dim da as new SqlDataAdapter( “SELECT * FROM StudentTable”,cnn)
Dim mycb As New SqlCommandBuilder(da)
da.Fill(mytable)
Dim myrow As DataRow = mytable.NewRow()
myrow("ID") = "thestudentid"
myrow("StudentName") = "John doe"
myrow("StudentID") = 12345
myrow("StudentClass") = "VB 101"
mytable.Rows.Add(myrow)
da.Update(mytable)
The CommandBuilder will automatically add insert, update and delete commands to the dataadapter (if your select command is one table only, otherwise you'll have to configure it manually).

Load Access from Datatable to Datset to DataGridView and Update Changes in DataGridView to Datatable

I need to load a DataTable from Microsoft Access into a DataSet using OleDb. I need to load that DataSet into a DataGridView. I then need to make changes to the DataGridView and update those changes in the original DataTable in Microsoft Access.
Here is my code so far:
Public tblName As String = "Criteria"
Dim ds As New DataSet()
Dim da As OleDbDataAdapter
Dim cmdBuilder As OleDbCommandBuilder
Dim Bsource As New BindingSource
Public Sub Show_Panel_Manage_Calculations()
Panel_Manage_Calculations.Show()
Nordeen_Investing_3.con.Open()
da = New OleDbDataAdapter("SELECT Calculation, [Interval], Formula FROM " & tblName & "", Nordeen_Investing_3.con)
cmdBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "Criteria")
Bsource.DataSource = ds
DataGridView_Manage_Calculations.DataSource = Bsource
Nordeen_Investing_3.con.Close()
End Sub
Private Sub Button_Update_Click(sender As Object, e As EventArgs) Handles Button_Update.Click
Nordeen_Investing_3.con.Open()
da.Update(ds, "Criteria")
Nordeen_Investing_3.con.Close()
End Sub
Right now my data from the DataTable is not being displayed in my DataGridView.
The DataSource expects a Table, not the whole DataSet. Also you don't need the BindingSource part. Sample code:
DataGridView_Manage_Calculations.DataSource = ds.Tables(0) 'By assuming that you want the first table