dynamically created datagridview columns not accessible unless added to a form...why?
We simply created a DataGridView control dynamically and bound it to a DataTable. We were tying to style certain columns. But, when we tried to access the columns we got a null reference. On further investigation we found that if we add the DataGridView control to the main form, and then try to access its columns, it works fine!!!
Code which throws error:
DataGridView gv = new DataGridView();
gv.DataSource = GetDataTable(); //binding it to datatable
Debug.Assert(gv.Columns == null);
Code which works fine:
DataGridView gv = new DataGridView();
gv.DataSource = GetDataTable(); //binding it to datatable
this.Controls.Add(gv); //adding to form
Debug.Assert(gv.Columns == null); //the assertion fails!
Why is this behaviour so? Is there a workaro开发者_开发技巧und for this?
I had a similar problem but I am not sure it could help you.
You can attach an handler to DataGridView.DataBindingComplete
event.
When the DataGridView
is shown in the main thread if would rise that event and there you have all columns created and accessible
Er, wee bit of a stab in the dark; but its likely because the columns generated by use of the AutoGenerateColumns
property require a BindingContext
to properly generate and manage the bindings for the cell values. Typically, that BindingContext wouldn't be able to be determined until the Parent control is set.
精彩评论