how to sort a datagridview by 2 columns

后端 未结 8 1367
北恋
北恋 2020-12-05 08:38

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:

8条回答
  •  执笔经年
    2020-12-05 09:05

    I use this solution when working with bound data. This works for our users, and displays the current sort criteria. All sorts are only in ascending order.

    Add a CheckBox, a TextBox, a ColumnHeaderMouseClick event, and code as shown. The CheckBox will toggle the TextBox's visibility, and clicking on any column header will add the sort criteria to the TextBox. To clear the TextBox, just double click in it.

            private void FooDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
            {
                if(chkMultiSort.Checked == true)
                {
                    string columnHeader = FooDataGridView.Columns[e.ColumnIndex].DataPropertyName;
                    txtMultiSort.Text += (columnHeader + ", ");
                    try
                    {
                        FooBindingSource.Sort = txtMultiSort.Text.Remove(txtMultiSort.Text.Length - 2);
                    }
                    catch
                    {
                        MessageBox.Show("Invalid Sort Data", "Information", MessageBoxButtons.OK, MessageBoxIcon.None);
                        txtMultiSort.Text = String.Empty;
                    }
                }
    
            }
    
            private void ChkMultiSort_CheckedChanged(object sender, EventArgs e)
            {
                if(chkMultiSort.Checked == true)
                {
                    txtMultiSort.Visible = true;
                }
                else
                {
                    txtMultiSort.Visible = false;
                    txtMultiSort.Text = String.Empty;
                }
            }
    
            private void TxtMultiSort_DoubleClick(object sender, EventArgs e)
            {
                txtMultiSort.Text = String.Empty;
            }
    
    

提交回复
热议问题