Create ADO.NET DataView showing only selected Columns

19,145

Solution 1

You can't do that, but you can create a copy of the table with only the columns you want :

DataView view = new DataView(table);
DataTable table2 = view.ToTable(false, "FirstColumn", "SecondColumn", "ThirdColumn");

Optionally you can return rows that have distinct values for the selected columns :

DataView view = new DataView(table);
DataTable table2 = view.ToTable(true, "FirstColumn", "SecondColumn", "ThirdColumn");

Solution 2

Well I can't see any reason for "wanting" to do that... Remember, a DataView is just a list of pointers to the rows in the original table, and there is obviously no way to remove columns from the the original table... at least not without affecting every other function utilizing that table... Just only use the columns you want...

Share:
19,145
JaysonFix
Author by

JaysonFix

Updated on June 05, 2022

Comments

  • JaysonFix
    JaysonFix almost 2 years

    In C# & .NET, can one create a DataView that includes only a proper subset of the DataColumns of a given DataTable?

    In terms of relational algebra, one assigns a RowFilter in order to perform a "selection" operation (σ). How would one perform a "projection" operation (π)?

  • JaysonFix
    JaysonFix almost 15 years
    Thank you, Thomas. I'd also like to be able to include calculated columns in "table2". For example, view.ToTable ( "FirstColumn * 2", "SecondColumn > 0", "TRIM(ThirdColumn)" ) .
  • Thomas Levesque
    Thomas Levesque almost 15 years
    create them in table and select them in ToTable, or add them to table2 after you created it...
  • Florian Feldhaus
    Florian Feldhaus over 9 years
    You can shorten this by using the DefaultView of the DataTabe: $DataTable.DefaultView.ToTable("FirstColumn", "SecondColumn", "ThirdColumn");
  • Smith
    Smith over 7 years
    @ThomasLevesque how do I add a condition like FirstColumn = 'comevalue'?
  • Thomas Levesque
    Thomas Levesque over 7 years
    @Smith you can add it when you create the view: new DataView(table) { RowFilter = "FirstColumn = 'somevalue'" } (or something like that)