为什么必须将 DataGridView 添加到 Form 才能获取数据?

发布于 2024-12-17 17:22:46 字数 351 浏览 4 评论 0原文

我必须将一个 datagridview 复制到另一个,以便在后台工作线程中迭代它,创建 Excel 导出。

制作副本是为了允许用户在导出过程中对原始 datagridview 进行一些更改。

因此,我创建了一个新的 DataGridView(以编程方式),并将原始 DataTable 的副本放入新 DataGridView 的 DataSource 属性中。 但是,我发现如果我不在任何表单的 Controls(列表)属性中添加 datagridview,RowCount 仍然等于 0...

有人可以解释一下吗?

注意:DataTable 的副本只是一个带有 Columns 的 copy() 的新 DataTable。

I had to copy a datagridview to another, in order to iterate through it within a backgroundworker thread, creating an excel export.

The copy was made to allow users to made some changes in the original datagridview, during the export.

So I created a new DataGridView (programatically), and put a copy of the original DataTable into the DataSource property of the new DataGridView.
However, I figured out that if I don't add the datagridview in the Controls (list) property of any Form, the RowCount still equals to 0...

Can someone can explain this?

Note : The copy of the DataTable is just a new DataTable with copy() of Columns.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

余生再见 2024-12-24 17:22:46

这很简单。当您刚刚创建 DataGridView(或任何其他 WinForms 或 Wpf 控件)时,它仅在 .Net 中创建。例如,没有为其创建系统窗口。当控件处于这种状态时,它不会出于优化目的应用任何绑定(为什么视觉控件应该做任何事情,而它是不可见的?:))。当您将控件添加到visible表单时,控件将创建其系统窗口(即其Handle属性将被初始化),并且它将按预期开始工作。
如果您想让任何可视控件按预期工作,但不真正显示它,您只需读取其 Handle 属性即可。这将强制控件创建系统窗口并完全初始化。
另外,对于 WPF 来说,这有点困难,因为您只能获取 Window 控件的句柄,并且为了获取它,您必须使用以下代码:

public IntPtr GetWpfWindowHandle(Window w)
{
   var interopHelper = new WindowInteropHelper(w);
   return interopHelper.Handle;
}

This is quite simple. When you just created your DataGridView (or any other WinForms or Wpf control) it is created only in .Net. E.g. there is no system window created for it. And while control is in this state, it don't apply any bindings for optimization purposes (why should visual control do anything, while it is invisible? :)). When you add your control to the visible form, control will have its system window created (i.e. its Handle property will be initialized) and it will start work as expected.
If you want to make any visual control to work as intented, but not really show it, you simply need to read its Handle property. This will force control to create a system window and fully initialize.
Also for WPF it is a bit harder, because you can get a handle only for Window control and in order to get it you have to use following code:

public IntPtr GetWpfWindowHandle(Window w)
{
   var interopHelper = new WindowInteropHelper(w);
   return interopHelper.Handle;
}
時窥 2024-12-24 17:22:46

请参阅此问题获取答案。在这种情况下,仅读取 Handle 是行不通的 - 我需要将 BindingContext 分配给网格。

See this question for an answer. In that instance, just reading the Handle didn't work - I needed to assign a BindingContext to the grid.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文