首页 > 解决方案 > 将 Access 数据加载到 DataGridView

问题描述

我的 Visual Studio 项目中有一个 MS Access 数据库作为连接。当我添加连接时,它会自动生成一些代码:

private void CruncherForm_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'wcMainDBDataSet.stations_NOAA' table. You can move, or remove it, as needed.
    this.stations_NOAATableAdapter.Fill(this.wcMainDBDataSet.stations_NOAA);
}

我已将该代码修改为以下内容:

private void CruncherForm_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'wcMainDBDataSet.stations_NOAA' table. You can move, or remove it, as needed.
    this.stations_NOAATableAdapter.Fill(this.wcMainDBDataSet.stations_NOAA);

    foreach (var row in this.wcMainDBDataSet.stations_NOAA.Rows)
    {
        this.wthrDB.Rows.Add(row);
    }
}

wthrDB是我的 DataGridView。我没有从我的数据网格中的 Access 数据库中获取 2 行。这样做的正确方法是什么?

一个想法:列之间是否需要一些链接?如果计算 ID(主键)列 Access 自动生成,我的数据网格视图中有 9 个定义的列和 Access 文件中的 10 个。如果是这样,在数据源场景中是如何完成的?

标签: c#winformsdatagridview

解决方案


DataGridView 有DataSource 属性,可以设置为DataTable。确保它实际上包含一些行(在 CruncherForm_Load 方法中设置断点并在调试模式下检查stations_NOAA)

private void CruncherForm_Load(object sender, EventArgs e)
{
    this.stations_NOAATableAdapter.Fill(this.wcMainDBDataSet.stations_NOAA);

    this.wthrDB.DataSource = this.wcMainDBDataSet.stations_NOAA;
}

也可能需要将DataPropertyName分配给 DataGridView 列


推荐阅读