将Access数据库添加到C#dataGridView(仅使用代码)

时间:2012-04-25 13:30:20

标签: c# ms-access datagridview dataset

我在表单上有2个dataGridViews,当我运行应用程序时,没有任何显示。我相信在代码中添加dataGridView信息,如下所示,我不需要使用Visual Studio的“服务器资源管理器”添加数据库。这将是多余的和/或更改dataGridView的填充结果,对吧?我在代码中遗漏了什么?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      DataSet ds = new DataSet();
      OleDbDataAdapter daOrders = new OleDbDataAdapter();
      OleDbDataAdapter daReceived = new OleDbDataAdapter();
      OleDbConnection vcon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Query Form\Database.accdb");    

      OleDbCommand slctOrders = new OleDbCommand("SELECT * FROM script_Orders ORDER BY script");
      daOrders.SelectCommand = slctOrders;
      daOrders.Fill(ds, "tblOrders");

      OleDbCommand slctReceived = new OleDbCommand("SELECT * FROM script_Received");
      daOrders.SelectCommand = slctReceived;
      daOrders.Fill(ds, "tblReceived");

      dgOrders.DataSource = ds.Tables ["tblOrders"];
      dgReceived.DataSource = ds.Tables ["tblReceived"];
    }
  }
}

1 个答案:

答案 0 :(得分:2)

尝试将连接传递到数据适配器......

OleDbCommand slctOrders = new OleDbCommand("SELECT * FROM script_Orders ORDER BY script", vcon);

我不确定这是否是你所缺少的(你可能还需要打开连接,vcon.Open()),但是连接对象和适配器之间必须有一些链接。