I have a custom control which inherits from DataGridView. It augments the control with some additional functionality (which exports the contents of each cell). I wo
David Hall's comment led me to here, which led me to look into the BindingContext of the grid. Sure enough, it's null, but by creating a new BindingContext for the grid control, binding the grid to the DataTable now populates the "Columns" collection.
public Form1()
{
InitializeComponent();
DataTable dataTable = new DataTable() { TableName = "Bob" };
:
DataGridView grid = new DataGridView { Name = "Tom" };
grid.BindingContext = new BindingContext();
grid.DataSource = dataTable;
int n1 = grid.Columns.Count; // returns three
}
Curiously enough, the order in which you set the binding context or the data source appears not to matter !