Search code examples
c#wpfwpfdatagrid

Loading a DataView into a DataGrid causes ShowDialog to hang?


I have this very straightforward code:

var xlData = Excel8OleDbHelper.ImportExcelFile(fileName);
var viewModel = new MyViewModel(xlData);

_window = new MyWindow(viewModel);
_window.ShowDialog();

The Excel8OleDbHelper.ImportExcelFile() method works, I can view the DataTable's content when debugging. The problem is that _window simply does not show up and the thread behaves as if it did (i.e. it's waiting for the unshown window to be closed).

If I change the code for this:

var viewModel = new MyViewModel(new DataTable());

_window = new MyWindow(viewModel);
_window.ShowDialog();

Then the window appears, but then of course with an empty grid.

The XAML for the grid:

<DataGrid x:Name="MyGrid" Margin="4" 
    IsReadOnly="True" SelectionUnit="Cell" 
    ItemsSource="{Binding Path=GridSource}" />

And the ViewModel's constructor:

public DataView GridSource { get; private set; }
public MyViewModel(DataTable dataSource)
{
    GridSource = dataSource.DefaultView;
}

This is my first time using a WPF data grid so maybe I'm doing something wrong here, but I really don't see how something wrong with the grid could prevent the window from showing up at all, without giving me an exception and actually freezing my app.

Any clues? I'll gladly supply more code if anything is missing!

UPDATE Loading an Excel workbook with 116 rows x 47 columns works; the file I need to load has 5,000+ rows x 47 columns - could it be that the WPF DataGrid requires paging for larger datasets? The WinForms DataGridView had no issues with it and was much faster, I assumed its WPF counterpart would work in a similar fashion. So the problem was that ShowDialog was waiting for the data grid to load the data. I assumed it was hung because I didn't expect the WPF DataGrid to take over a minute to do what the WinForms DataGridView did instantly.


Solution

  • Now that we have identified that the issue with the volume of the data:

    • Do you have row and column virtualization turned on ? You can set EnableRowVirtualization=true on the datagrid
    • Are you using auto-sized columns ? Recomputing optimal size for every new row/column can be a perf drag - Try using a fixed column size or a proportional (1*) size. You can try a similar approach with Height for Rows.