问题
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;
回答1:
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.
回答2:
And another scenarios creating a new DataView is preferable, it is asp global (app variable) datatable shared between sessions. Defaultview with rowfilter not preferable, because applied filter affect all sessions defaultview. So you must create dataview for every session. vb.net
Application("dt") = New DataTable() - persits across sessions
Application("dt").DefaultView.RowFilter="Field = Value" - not preferable because it apply all sessions
Session("dv") = New DataView(Application("dt"))
Session("dv").RowFilter="Field = Value" - preferable
来源:https://stackoverflow.com/questions/31177899/new-dataview-vs-defaultview-of-a-datatable