This project has moved. For the latest updates, please go here.

Speed up printing to DataGridView

Sep 13, 2011 at 8:20 PM
Edited Sep 13, 2011 at 10:02 PM

I am importing a spreadsheet that is roughly 30co x 1500ro. It around 15 seconds to import the entire thing into the actual datagrid, which seems glacial to me.  Is this type of performance typical, or can it be optimized through code?

here's how i am doing it:

        public void PopulatePreviewWindow()
        {
            FileInfo existingFile = new FileInfo(txtExcelLoc.Text);
            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int TotalColumns = worksheet.Dimension.End.Column;
                int TotalRows = worksheet.Dimension.End.Row;
                for (int col = 0; col < TotalColumns; col++)
                {
                    dgvPreview.Columns.Add(worksheet.Cells[1, (col+1)].Value.ToString(), worksheet.Cells[1, (col+1)].Value.ToString());
                }
                dgvPreview.RowCount = TotalRows;
                for (int row = 1; row < TotalRows; row++)
                {
                    for (int col = 0; col < TotalColumns; col++)
                    {
                        try
                        {
                            dgvPreview[col, row].Value = worksheet.Cells[(row + 1), (col + 1)].Value.ToString();
                        }
                        catch
                        {
                            dgvPreview[col, row].Value = " ";
                        }
                    }
                }
	}
}
I am still new to C# coding, so this probably isn't the best implementation, but if it can be made to work more quickly, please explain how(and why). 
Also, the try/catch is in place because there are some images in these spreadsheets, and they were causing crashes.
*edit* Nevermind, i figured it out. The try/catch was slowing it down.  Changed it to an if statement and now the sheet loads in less than a second.
lee

 


Sep 21, 2011 at 4:38 PM

Try to export your Excel data to a DataTable and Bind the DataTable to DataGrid