How to Filter a DataView | C#

The DataView feature empowers you to generate diverse perspectives of the data residing within a DataTable. With DataView, you have the ability to customize and tailor the data views according to specific requirements. This powerful functionality enables sorting, filtering, and searching operations on a DataTable, in addition to facilitating the addition of new rows and modification of existing content.

Filter a DataView

By using DataView, developers can effortlessly transform the presentation of data, tailoring it to specific requirements. Through sorting capabilities, data can be organized in ascending or descending order based on desired fields. Filtering empowers the extraction of specific subsets of data based on defined criteria, facilitating efficient data retrieval. Additionally, the search functionality enables quick and targeted data exploration within the DataTable. The ability to add new rows and modify existing content further enhances the dynamic nature of DataView, enabling seamless data manipulation within the DataTable.

The following C# source code creates a view that shows all Product Details where the Product Price less than 3000. 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, "Filter DataView"); adapter.Dispose(); command.Dispose(); connection.Close(); dv = new DataView(ds.Tables[0], "Product_Price < = 3000", "Product_Name", DataViewRowState.CurrentRows); dataGridView1.DataSource = dv; } catch (Exception ex) { MessageBox.Show (ex.ToString()); } } } }

Conclusion

DataView serves as a powerful tool for creating customizable views of data stored within a DataTable. Its versatile functionality enables sorting, filtering, searching, and data manipulation operations, providing developers with the ability to tailor data views according to specific requirements. Multiple DataViews can be created for a DataTable, enabling simultaneous exploration of data from different perspectives. By using DataView, developers can unlock the full potential of their data, facilitating effective data analysis and decision-making processes.