Fill a DataGridView from a DataSet (code-wise)

Today I’m goin to explain how you can show your data from a table inside a DataGridView.

We’ll run a simple SELECT command against our database, fill our dataset and then display the contents of our dataset in our datagridview

First off we’ll start by defining the objects we need:

'Variable declaration, scope: global
'Note: MyDatabase is your database. In this example the database will be located where the *.exe is located of our program
Dim g_oCon As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MyDatabase.accdb;Persist Security Info=False;")
Dim g_oSelect As New OleDb.OleDbCommand("", oCon)  'Our SELECT command
Dim g_oDR As OleDb.OleDbDataReader 'Our data reader
Dim g_oDA As New OleDb.OleDbDataAdapter("", oCon) 'Our data adapter
Dim g_oDS As New DataSet 'Our dataset

Now that we have these, we can get started.
I’ll create a seperate sub where we can do all the work:

'Subroutine to fill our dataset and show it's contents in our datagridview
Private Sub m_fnShowData()
	Try
		'Set our query
		g_oSelect.CommandText = "SELECT * FROM MyTable"

		'Open up the connection
		g_oCon.Open()

		'Set the select command for our data adapter
		g_oDA.SelectCommand = g_oSelect

		'Fill the dataset
		g_oDA.Fill(g_oDS, "MyTable")

		'Set what the datagridview has to display
		g_oDGV.DataSource = g_oDA.Tables("MyTable")

		'Close the connection
		g_oCon.Close()
	Catch ex As OleDbExeption
		MessageBox.Show(ex.ToString)
	End Try
End Sub

And there we go, a DataGridView filled with the exact same data as found in our table

Leave a Reply

Your email address will not be published.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.