Question I can't populate my Datagrid from Dataset

Adrian Mepham

New member
Joined
Jan 5, 2011
Messages
2
Programming Experience
Beginner
Hi everyone,

I am new here so forgive me if this is the wrong section for my question. My problem is that I can't populate a datgrid with the contents of a dataset. Having searched for the last few days to try and resolve this, I have given up and thought I would try here.

As you can tell from the code I am very new to this and any suggestions for improvement will be most welcome. I can see that the dataset is populated ok via the visualizer, I have a datagrid 'dgBOM' which I want to display the results. A popular solution in my searches was to add '.DataSource' but when I type the '.' after dgBOM the Datasource option is not there.

Any help would be much appreciated.

Thank you.

Code:

Public Sub Connect()
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim ds As DataSet
Dim da As OleDbDataAdapter
Dim dt As DataTable
Dim drow As DataRow
Dim PartColumn As DataColumn
Dim CostColumn As DataColumn
dt = New DataTable("BOM")
ds = New DataSet("BOM")
PartColumn = New DataColumn("PartNo")
CostColumn = New DataColumn("Cost")
da = Nothing
cn = Nothing
dr = Nothing
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\Ls-wtgl834\share\Adrian\PriceLists\WAP-PriceLists.mdb;User ID=Admin;)
cn.Open()
cmd = New OleDbCommand("select * from Inventory", cn)
dr = cmd.ExecuteReader
da = New OleDbDataAdapter(cmd)
dt.Columns.Add(PartColumn)
dt.Columns.Add(CostColumn)
While dr.Read()
If dr(0) = FBladeExtNo Then
FrontBladeCost = dr(1)
drow = dt.NewRow()
drow("PartNo") = FBladeExtNo
drow("Cost") = FrontBladeCost
dt.Rows.Add(drow)
ds.Tables.Add(dt)
Exit While
End If
End While
dgBOM.ItemsSource = ds
Catch
End Try
dr.Close()
cn.Close()
End Sub
 
I am using this method and it works for me perfectly.
hope it gonna work for you as well

I assume that you already have your connexion open and con in my example is my OleDb.OleDbConnection

sql = "Select * FROM tbName"
cmd = New OleDb.OleDbCommand(sql, con)
Dim reader As OleDb.OleDbDataReader
reader = cmd.ExecuteReader

Dim table As DataTable
table = New DataTable("TableName")

Dim col1 As New DataGridViewTextBoxColumn
col1.DataPropertyName = "col1Name"
col1.Name = "col1Name"
dataGridName.Columns.Add(col1)

and you do the same thing for number n columns.

then you start populating your datagrid

while reader.read()


dataGridName.Rows.Add()
dataGridName.Rows(i).Cells("col1Name").Value = reader.Item("colNameInMDBTable") 'i represents the row number desired

end while

that's it!

if you have any question dont hesitate to ask

Good Luck
 
Thanks for your help Usra. I shall give this a try and let you know how I get on. I'm only working a half day today so I will probably do it Monday.
Have a good weekend and thanks again for taking the time to help.
Adrian.
 
Back
Top