Create new DataTable from the DefaultView of the another DataTable

The following article demonstrates how to create new DataTable from the DataView or DefaultView of another DataTable. The general requirement for doing this is that once you have retrieved DataTable from a data source and than you may need to sort or filter the data without retrieving it again. You can use the ToTable() method that creates and returns a new DataTable object based on rows in an existing DefaultView of the DataTable.

In the following example we create a DataTable that contains the project id, project name and their status. Next we create a new DataTable from the existing DataTable after applying row filter.

C#

SqlDataAdapter adapter = new SqlDataAdapter(
        "SELECT Pid, ProjectName, Status " +
        "from tblProject", 
           ConnectionString);
DataTable dt = new DataTable();
adapter.Fill(dt);
dt.DefaultView.RowFilter = "Status='Pending'";
 
DataTable newDt = new DataTable(); 
newDt = dt.DefaultView.ToTable();

In the vb.net, you need to write the following code:

VB.Net

Dim adapter As New SqlDataAdapter("SELECT Pid, ProjectName, " & _
     "Status from tblProject", ConnectionString)
Dim dt As New DataTable()
adapter.Fill(dt)
dt.DefaultView.RowFilter = "Status='Pending'"
 
Dim newDt As New DataTable()
newDt = dt.DefaultView.ToTable()

Replace the ‘ConnectionString‘ from your valid SQL database connection string.