问题
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.
回答1:
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;
}
回答2:
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.
来源:https://stackoverflow.com/questions/8256762/why-must-i-add-a-datagridview-to-a-form-in-order-to-get-the-data