编程方式从数据表中创建的DataGridView [英] Programmatically create DataGridview from DataTable

查看:95
本文介绍了编程方式从数据表中创建的DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

DataTable table = new DataTable();

//DataTable is filled with values here...

DataGridView grid = new DataGridView();

foreach (DataColumn column in table.Columns)
{
    grid.Columns.Add(column.ColumnName, column.ColumnName);
}

grid.DataSource = table;

当我检查电网数据源属性指示的行数是正确的。但是, grid.Rows 计数为零。

When I examine grid, the DataSource attribute indicates that the number of rows is correct. However, the grid.Rows count is zero.

在相反,如果我创建了一个 DataGridView的上一个WinForm,然后分配它的数据源数据表 DataGridView.Rows 将被自动添加。

In contrast, if I create a DataGridView on a winform, and then assign its DataSource to a DataTable, the DataGridView.Rows will be added automatically.

什么代码,我在这里缺少,为了有 DataGridView.Rows 数是否正确?

What code am I missing here, in order to have the DataGridView.Rows count correct?

推荐答案

通过添加此 DataGridView的控件到窗体编程工程:)
有人会告诉我们为什么?

By adding this DataGridView control to the form programmatically it works :) Anybody would tell us why?

DataTable table = new DataTable();

//DataTable is filled with values here...

DataGridView grid = new DataGridView();

// assuming (this) is a reference to the current form
this.Controls.Add(grid);

grid.DataSource = table;

这篇关于编程方式从数据表中创建的DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆