How to add new row in a DataView

The DataView provides different views of the data stored in a DataTable. DataViews can be created and configured on both design time and run time . We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView Property of the DataTable. We can create multiple DataViews for any given 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.

We can add new rows in the DataView using AddNew method in the DataView. The following C# source code shows how to add new row in a DataView . Create a new C# project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following C# Source Code on button click event.

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, "Add New");

                dv = new DataView(ds.Tables[0]);
                DataRowView newRow = dv.AddNew();
                newRow["Product_ID"] = 7;
                newRow["Product_Name"] = "Product 7";
                newRow["Product_Price"] = 111;
                dv.Sort = "product_id";

                dataGridView1.DataSource = dv;
            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