Search code examples
c#datatabledataview

New DataView vs. DefaultView of a DataTable


Why would you construct a new DataView instead of using the DefaultView of the DataTable in C#?

What are the scenarios creating a new DataView is preferable?

What are the advantages and disadvantages of both?

var dataView = new DataView(dataTable);

vs

var dataView = dataTable.DefaultView;


Solution

  • The DefaultView has the advantage of being there already by default, as the name implies.

    Additional DataViews have the advantage of allowing you to keep several of them ready and in use in parallel.

    So you can filter and sort 3 of them in different ways and bind 3 different controls, e.g. three DataGridViews or a DGV and the Items of a ComboboxCell to them independently.

    Quoting from this post:

    A dataview is a view on a datatable, a bit like a sql view. It allows you to filter and sort the rows - often for binding to a windows form control. Additionally, a DataView can be customized to present a subset of data from the DataTable. This capability allows you to have two controls bound to the same DataTable, but showing different versions of the data.