dynamically created datagridview columns not accessible unless added to a form...why?

Posted by deostroll on Stack Overflow See other posts from Stack Overflow or by deostroll
Published on 2010-06-17T07:10:53Z Indexed on 2010/06/17 7:13 UTC
Read the original article Hit count: 360

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms