How to update rows in DataView

The DataView class in ADO.NET provides a versatile mechanism for creating different views of the data stored in a DataTable. These views can be customized to suit specific requirements and offer functionalities such as sorting, filtering, and searching the data within a DataTable. Additionally, DataViews allow us to add new rows and modify existing data in the underlying DataTable.

One notable advantage of DataViews is their ability to support multiple views for a single DataTable. This means that we can create and manage multiple DataViews, each with its own unique configuration and criteria, based on the same underlying DataTable.

Updating data within the view

In addition to viewing and manipulating data, DataViews also facilitate updating data within the view. To demonstrate this capability, 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 update data within a DataView, enabling the modification of existing values and ensuring data consistency within the underlying DataTable.

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, "Update") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "", "Product_Name", DataViewRowState.CurrentRows) Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Product not found") Else dv(index)("Product_Name") = "Product11" MsgBox("Product Updated !") End If DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class