How to edit row in a DataView | C#

Developers can use DataView and have the power of presenting the data in a table with different sort orders. This means that users can view the data in ascending or descending order, depending on the selected fields. Furthermore, DataView supports the filtering of the data so that the pieces of information are shown based on the expression of a filter or a row state.

Edit row in a DataView

In data management, it is worth noting that DataView offers the capability to update the data it represents. Through appropriate methods and techniques, developers can modify the content within a DataView, thereby reflecting the changes in the underlying DataTable.

The following C# source code shows how to update data 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.

Full Source C#
using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } 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); 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); int index = dv.Find("PRODUCT5"); if (index == -1) { MessageBox.Show ("Product not found"); } else { dv[index]["Product_Name"] = "Product11"; MessageBox.Show("Product Updated !"); } dataGridView1.DataSource = dv; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } }

Conclusion

DataView is a powerful tool for providing diverse views of the data stored in a DataTable. It facilitates sorting, filtering, and searching operations on the data, while also allowing the addition of new rows and modification of existing content. Multiple DataViews can be created for a single DataTable, enhancing the flexibility and exploration of data. Using DataView, developers can present data in various sort orders, filter data based on row state or filter expressions, and perform updates to the data represented within the DataView.