How to delete rows in DataView
The DataView class in ADO.NET offers various functionalities for creating different views of the data stored in a DataTable. These views can be utilized for sorting, filtering, and searching data within the DataTable. Additionally, DataViews allow for the addition of new rows and modification of existing content within the underlying DataTable. Furthermore, it is also possible to delete data from a DataView.
Delete data from a DataView
To demonstrate the process of deleting data from a DataView, the following source code provides an example. To begin, create a new VB.NET project and 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 illustrates the necessary steps to delete data from a DataView, ensuring the removal of specific rows from the view.
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, "Delete Row")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = New DataView(ds.Tables(0), "", "Product_ID", DataViewRowState.CurrentRows)
dv.Table.Rows(3).Delete()
DataGridView1.DataSource = dv
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class