Search code examples
c#dataview

Convert Sorted DataView to Typed DataTable


i have a strong typed DataTable named Account wich i sorted on Account.FullName:

DataView dvAccount = new DataView(dtAccount)
dvAccount.Sort = "FullName desc";

The fullname is a generated field from my DataSet after my query, based on first name, middle, last etc. This means that sorting by SQL query is not an option unfortunately.

First i tried to get the table like this:

dtAccount = dvAccount.Table()

But this gave me the original Table the Dataview was based on. So after reading online i found out that i should have used the DataView.ToTable() function instead of the DataView.Table() function:

dtAccount = dvAccount.ToTable() as dsAccount.AccountDataTable; // returns null
dtAccount = ((dsAccount.AccountDataTable) dvAccount.ToTable()); // gives Convertion to Typed Datatable Error

Now i get the problem that my Account Table is Strong typed. so searching online tells me that i could go with the DataTable.Merge() Function or DataTable.ImportRow() for each row but these are told to be a very heavy procedures because every row gets checked on the Type. what's the best practice solution to this situation?


Solution

  • I just had the same issue. I used this kind of solution.

            dtAccount = New dsAccount.AccountDataTable;
            dtAccount.Merge(dvAccount.ToTable());
    

    This works fine for me. Tell me if you have a better one.