Loading datagridview in VB.NET programmatically using dataset
80,608
Solution 1
You can get the table from the data source via the index:
dataGridReport.DataSource = ds.Tables(0)
Solution 2
dataGridReport.DataSource = ds.Tables("Tablename")
Author by
user961627
Updated on May 17, 2020Comments
-
user961627 almost 4 years
I've created a datagridview,
dataGridReport
in the Designer view of VB 2010. I'm then using a query to fill a dataset, and I want this dataset to populate the datagridview... but it doesn't seem to work.This is my code:
Dim con As New OleDb.OleDbConnection con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administrator\Documents\MenuDB.accdb" con.Open() Dim ds As DataSet = New DataSet Dim adapter As New OleDb.OleDbDataAdapter Dim sql As String sql = @"SELECT OrderDate, MenuItem FROM MenuItems, Orders WHERE Orders.itemID = MenuItems.ID AND Format(Orders.OrderDate,'mm/dd/yyyy') >= #" + fromDate + "# AND Format(Orders.OrderDate,'mm/dd/yyyy') <= #" + toDate + "#" adapter.SelectCommand = New OleDb.OleDbCommand(sql, con) adapter.Fill(ds) dataGridReport.DataSource = ds
I know something's missing now - I've looked around and most people seem to use something like
dataGridReport.DataSource = ds.Tables('somereference')
But mine is a dynamically created dataset from a query joining two tables, it's not something stored among the project Data Sources. I also haven't bound the datagridview to any datasource via its properties. What am I missing?
(By the way, the sql query is correct, I've tested it and returns expected results).
-
user961627 over 11 yearsI've tried that, but I get the error
DataBind is not a member of System.Windows.Forms.DataGridView
-
user961627 over 11 yearsOkay I retried it - I kept the first line you supplied but removed the second, and now it's working! Thanks a lot! If you edit your answer to remove the second line, I'll select it as the answer.
-
Victor Zakharov over 11 years@user961627: funny thing - I was going to suggest that (i.e. remove DataBind), but you already figured. There is no DataBind member for DataGridView. :)
-
Dennis Traub over 11 years@user961627 yes, you're right. I confused it with a third-party DataGrid control that needs to be explicitly bound.
-
DimaSan almost 7 yearsWhile this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.