How to add new rows in DataView

The DataView in ADO.NET offers a powerful feature that allows us to create and configure different views of the data stored in a DataTable. These DataViews can be created and customized both during the design phase of the application and dynamically at runtime, providing flexibility in managing data presentation.

There are two primary ways to create a DataView. The first method involves using the DataView constructor, which initializes a new instance of the DataView class. This constructor allows us to specify the DataTable that will serve as the data source for the DataView. The second method involves creating a reference to the DefaultView property of the DataTable. This property automatically provides a DataView associated with the DataTable, simplifying the DataView creation process.

AddNew method

In addition to providing different views of the data, DataViews offer functionality to add new rows to the DataView. This can be achieved using the AddNew method, which allows us to insert a new row into the DataView. This method simplifies the process of adding data dynamically to the DataView, enabling efficient data manipulation and modification.

To demonstrate the process of adding a new row in a DataView, the following source code illustrates the necessary steps. In a new VB.NET project, add a DataGridView and a Button to the default Form Form1. Then, copy and paste the provided source code into the button click event. This code snippet demonstrates how to utilize the AddNew method to insert a new row into the DataView, enhancing the interactivity and versatility of your application.

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, "Add New") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) Dim newRow As DataRowView = dv.AddNew() newRow("Product_ID") = 7 newRow("Product_Name") = "Product 7" newRow("Product_Price") = 111 newRow.EndEdit() dv.Sort = "product_id" DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class