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 :)

  1. Thank you so much! I had the very same problem…

  2. Hi TimVan

    I want create new property ( Rows , Cols) to DataGridView
    (->So I can choice and set Rows munber and cols munber from form design)
    I have create a new UserControl
    ———-
    Public Property Cols() As Integer
    Get
    Return Me._Cols
    End Get
    Set(ByVal value As Integer)
    Me._Cols = value
    Me.Invalidate()
    End Set
    End Property
    ——————
    on form design display property Cols, I don’t know after that what I must todo
    Please help me !

  3. @Le Hai

    I’m not sure what you’re trying to achieve. A DataGridView already has properties ColumnCount and RowCount.

  4. The performance improvement is un-believable when you disable columnheaderresizing! BRILLIANT

    For those interested in the VB.NET translation, (and I hope the author does notmind) here it is


    Dim columns As DataGridViewColumn() = New DataGridViewColumn(749) {}
    For i As Integer = 0 To columns.Length - 1
    Dim column As DataGridViewColumn = New DataGridViewTextBoxColumn()
    column.FillWeight = 1
    columns(i) = column
    Next
    Me.dataGridView1.Columns.AddRange(columns)

  5. Dennis van der Pool

    Thanks!!! Finally my performance issue with DataGridView has been solved.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>