views:

94

answers:

2

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 workaround for this?

A: 

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.

Reddog
PS. What's wrong with adding it as a child control? What else do you want to use it for?
Reddog
+1  A: 

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

marco.ragogna
Yes, its amazing how I missed this out...! :)
deostroll
DataGridView is heavy :D I missed out many things too
marco.ragogna