使用数据集以编程方式在 VB.NET 中加载 datagridview
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13544462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading datagridview in VB.NET programmatically using dataset
提问by user961627
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.
我在dataGridReport
VB 2010 的设计器视图中创建了一个 datagridview 。然后我使用查询来填充数据集,我希望这个数据集填充 datagridview ......但它似乎不起作用。
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')
我知道现在缺少一些东西-我环顾四周,大多数人似乎都在使用类似的东西 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?
但是我的数据集是从连接两个表的查询中动态创建的数据集,它不是存储在项目数据源中的东西。我也没有通过其属性将 datagridview 绑定到任何数据源。我错过了什么?
(By the way, the sql query is correct, I've tested it and returns expected results).
(顺便说一下,sql 查询是正确的,我已经测试过了并返回了预期的结果)。
回答by Dennis Traub
You can get the table from the data source via the index:
您可以通过索引从数据源获取表:
dataGridReport.DataSource = ds.Tables(0)
回答by saeed ahmed
dataGridReport.DataSource = ds.Tables("Tablename")
回答by wazir
Dim con As New OleDb.OleDbConnection
con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
DataSource=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,sql)
dataGridReport.DataSource = ds.tables(sql)