简体   繁体   中英

DataGridView - Adding columns without constant horizontal scroll bar update (Winforms)

I have a DataGridView and I need to add several (say 20) columns to it dynamicly. When I do it like this

foreach (var columnName in ColumnNames)
     dataGridView.Columns.Add(columnName, columnName);

horizontal scroll bar tries to stay up to date every time new column is added. So user sees strange scroll bar shrinking. I need to update horizontal scroll bar only once when all columns are added. How do I accomplish this?
PS I tried to do it like this:

((System.ComponentModel.ISupportInitialize)(dataGridView)).BeginInit();
dataGridView.SuspendLayout();

foreach (var columnName in ColumnNames)
{
     dataGridView.Columns.Add(columnName, columnName);
}

((System.ComponentModel.ISupportInitialize)(dataGridView)).EndInit();
dataGridView.ResumeLayout(false);

but it didn't help.

You could use DataGridViewColumnCollection.AddRange . This might help with the updating.

dataGridView.Columns.AddRange(Columns);

An example of AddRange given columns name (untested but should work):

// Assuming ColumnNames is a list of column names    
DataGridViewColumn[] columns_to_add = 
   new DataGridViewColumn[ColumnNames.Count];
for(int i = 0; i < ColumnNames.Count; i++)
{
   // Add whatever column type you want
   columns_to_add[i] = new DataGridViewTextBoxColumn();
   columns_to_add[i].HeaderText = ColumnNames[i];
   columns_to_add[i].Name = ColumnNames[i];
}
dataGridView.Columns.AddRange(columns_to_add);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM