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?