Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

14 Sep 2006

Adding DataGridViewColumns (lots of them)

Last couple of days i’ve been trying to add a couple (750+) columns into a DataGridView. Initially i tried the following

this.dataGridView1.ColumnCount = 750;

The code above results in the following error: Sum of the columns’ FillWeight values cannot exceed 65535. Then i tried the following

DataGridViewColumn[] columns = new DataGridViewColumn[750];
for ( int i = 0; i < columns.Length; ++i ) 
{ 
	DataGridViewColumn column = new DataGridViewColumn(); 
	column.CellTemplate = new DataGridViewTextBoxCell(); 
	column.FillWeight = 1; columns[i] = column; 
} 
this.dataGridView1.Columns.AddRange( columns );

This results in the following error: At least one of the DataGridView control’s columns has no cell template. Thus i tried the following

DataGridViewColumn[] columns = new DataGridViewColumn[750];
for ( int i = 0; i < columns.Length; ++i ) 
{ 
	DataGridViewColumn column = new DataGridViewTextBoxColumn(); 
	column.FillWeight = 1; columns[i] = column; 
} 
this.dataGridView1.Columns.AddRange( columns ); 

This code works but the AddRange call took about 15 seconds to complete. With the aid of a collegue and Reflector i set the ColumnHeadersHeightSize to DisableResizing. This reduced the calltime to less than 0.5 seconds 🙂