How to Sort a DataView
The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search data in a DataTable , additionally we can add new rows and modify the content in a DataTable. DataViews can be created and configured on both design time and run time . Changes made to a DataView affect the underlying DataTable automatically, and changes made to the underlying DataTable automatically affect any DataView objects that are viewing that DataTable. More over a DataView provides a dynamic view of data in the underlying DataTable: the content, ordering, and membership reflect changes as they occur.
We can sort single or multiple fields in a DataView , also we can specify the sort order like ASC (ascending) and DESC (descending) . 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.
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());
}
}
}
}
|
|