How to Sort a DataViewv | C#

The DataView functionality offers diverse perspectives on the data stored within a DataTable. It provides the ability to sort, filter, and search data within the DataTable, and additionally allows for the addition of new rows and modification of existing content. DataViews can be created and configured at both design time and runtime, offering flexibility in adapting to changing data requirements.

When modifications are made to a DataView, they automatically propagate to the underlying DataTable, ensuring seamless synchronization. Similarly, changes made to the underlying DataTable are automatically reflected in any DataView objects that are currently viewing that DataTable. This bidirectional relationship ensures that any updates or modifications made to the data are immediately reflected in all associated views.

Sort a DataView

DataViews offer the flexibility to sort data based on single or multiple fields. Developers have the option to specify the sort order as ascending (ASC) or descending (DESC), enabling fine-grained control over the arrangement of data within the DataView.

The following C# example creates a View and apply sort on the column Product_Price in descending order. 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, "Sort DataView"); adapter.Dispose(); command.Dispose(); connection.Close(); dv = new DataView(ds.Tables[0], "Product_Price > 3000", "Product_Price Desc", DataViewRowState.CurrentRows); dataGridView1.DataSource = dv; } catch (Exception ex) { MessageBox.Show (ex.ToString()); } } } }

Conclusion

The DataView functionality provides valuable tools for manipulating and visualizing data stored in a DataTable. With features such as sorting, filtering, searching, and dynamic updates, DataViews offer a comprehensive and dynamic view of the underlying data, facilitating effective data management and presentation in various scenarios. Additionally, the ability to specify sort orders enhances the versatility of DataViews, allowing for precise arrangement of data based on specific requirements.