How to create a new DataTable from the DataView

The DataView provides different views of the data stored in a DataTable. That is we can customize the views of data from a DataTable. Changes made to a DataView affect the underlying DataTable automatically, and changes made to the underlying DataTable automatically affect any DataView objects that are viewing that DataTable. Note that if you create a DataView using the constructor that does not take any arguments, you will not be able to use the DataView until you have set the Table property.

A DataView enables you to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications. We can create a new DataTable from the DataView . We can use the ToTable method to copy all the rows and columns, or a subset of the data into a new DataTable .

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)
            string connetionString = null;
            SqlConnection connection ;
            SqlCommand command ;
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            DataView dv ;
            string sql = null;
            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            sql = "Select * from product";
            connection = new SqlConnection(connetionString);
                command = new SqlCommand(sql, connection);
                adapter.SelectCommand = command;
                adapter.Fill(ds, "Copy to DataTable");

                dv = new DataView(ds.Tables[0], "Product_Price <= 2000", "Product_ID", DataViewRowState.CurrentRows);
                DataTable dTable ;
                dTable = dv.ToTable();

                dataGridView1.DataSource = dTable;
            catch (Exception ex)
                MessageBox.Show (ex.ToString());
} (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About