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.


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

In the, you need to write the following code:


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

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