为什么必须将DataGridView添加到窗体中才能获取数据? [英] Why must I add a DataGridView to a Form in order to get the data?

查看:113
本文介绍了为什么必须将DataGridView添加到窗体中才能获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将一个datagridview复制到另一个视图,以便在backgroundworker线程中进行遍历以创建excel导出。

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

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

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

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

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...

有人可以解释吗?

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

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

推荐答案

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

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;
}

这篇关于为什么必须将DataGridView添加到窗体中才能获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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