How to create a new DataTable from DataView

DataView class in ADO.NET offers versatile capabilities for creating custom views of the data stored in a DataTable. These views can be tailored to specific requirements, enabling us to manipulate and present the data in a desired manner.

An interesting aspect of DataViews is that any changes made to the view are automatically reflected in the underlying DataTable. Likewise, any modifications made to the DataTable are immediately propagated to all DataView objects that are currently observing that DataTable. This two-way synchronization ensures consistency and coherence between the DataView and the DataTable.

ToTable method

In addition to providing different views of the data, the DataView class also allows us to create a new DataTable based on the contents of the DataView. This can be accomplished using the ToTable method, which offers flexibility in copying the rows and columns from the DataView into a new DataTable. We have the option to copy the entire dataset or a subset of the data, depending on our requirements.

Full Source VB.NET
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Copy to DataTable") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price <= 200", "Product_ID", DataViewRowState.CurrentRows) Dim dTable As DataTable dTable = dv.ToTable DataGridView1.DataSource = dTable Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class