Possible Duplicate:
Issue with displaying SQL result in DataGridView
I’ve kind of asked this question before but never got it sorted. Basically I am trying to populate a datagridview on my form with the results of an SQL query. I get no errors from this code but I do just get a completely blank datagridview i.e it does not show a thing, not even the column headings.
Also please note I know im currently open to SQL injection on my sql, I just want to get this working before I sort that.
Here is my whole class code:
Imports System.Data.OleDb
Imports System.Data
Public class TechScreen_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0: Data Source = C:\Users\Dave\Documents\jobList.mdb;")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM jobList WHERE techID = " & TechScreenID &"", con)
con.Open()
Dim DA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim mydataset As DataSet = New DataSet
DA.Fill(mydataset, "MyTable")
DataGridView1.DatSource = mydataset.Tables("MyTable").DefaultView
con.Close()
con = Nothing
End sub
End class
First off, while it may or may not be the source of your problem, the line:
Contains a typo. Should be DataGridView1.DataSource. Seems like this would have caused a compiler error though.
Other than that, try simplifying things similar to the below, and if you still have the binding problem, step through in the debugger to make sure everything is working as expected. Also, check that the “Autogenerate Columns” property on your dgv control is set to true.
I am not clear on some of what you are trying to do, so the following is a very general example of how I would approach this.
and use My.Settings.MyConnectionStringName to refer to it.
disposal of objects within the blocks scope for you, and is generally
a cleaner way to go.
that comes with Data Sets which a simple data table will do.
separating the data retrieval from assignment to a UI control. Even
more, I would probably go the next step, and separate the control
assignment from the Form Load event as well. You may well find that
there are multiple places in your form which require the datasource
to refresh or reset.
There are a variety of ways to approach this, and mine is not necessarily the “popular way. However, the following worked for me just now.
Simplify your code, and employ some refactoring: