Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort a datagridview by 2 columns

How do I sort a DataGridView by two columns (ascending)? I have two columns: day and status.

If I need to sort by one column, I do:

this.dataGridView1.Sort (this.dataGridView1.Columns["day"], ListSortDirection.Ascending);

But for two?

like image 462
user1112847 Avatar asked Jan 17 '12 08:01

user1112847


1 Answers

If your DataGridView is databound, you can sort your Datatable view and rebind to datatable as below:

private DataGridView dataGridView1 = new DataGridView();
private BindingSource bindingSource1 = new BindingSource();

private void Form1_Load(object sender, System.EventArgs e)
{
    // Bind the DataGridView to the BindingSource        
    dataGridView1.DataSource = bindingSource1;
    SortDataByMultiColumns(); //Sort the Data
}

private void SortDataByMultiColumns()
{
    DataView view = dataTable1.DefaultView;
    view.Sort = "day ASC, status DESC"; 
    bindingSource1.DataSource = view; //rebind the data source
}

OR, without using bindingsource and binding directly to DataView:

private void SortDataByMultiColumns()
{
    DataView view = ds.Tables[0].DefaultView;
    view.Sort = "day ASC, status DESC"; 
    dataGridView1.DataSource = view; //rebind the data source
}
like image 198
VSS Avatar answered Oct 07 '22 16:10

VSS