eranfu
eranfu

Reputation: 55

C# Winforms - Secondary sort of unbound DataGridView

apologies for the lame looking "grids" :(

I have an unbound data grid with 2 columns (Name and Status), and automatic sort on both columns. The alphabetical sorting on Name is not maintained when sorting by Status. It may look like this:

Name / Status

E / X

C / X

A / X

B / Y

D / Y

I'm trying to get the Status column to be sorted alphabetically, with secondary (always ASCENDING) sort on Name. This is the expected result (Status Ascending):

Name / Status

A / X

C / X

E / X

B / Y

D / Y

or with Status Descending

Name / Status

B / Y

D / Y

A / X

C / X

E / X

I know I probably need to programmatically sort on Status, but not sure how to implement it, nor how to trigger it (wouldn't overriding the ColumnHeaderMouseClick disable the automatic sorting on Name?).

Appreciate any ideas or leads!

Upvotes: 2

Views: 858

Answers (3)

TaW
TaW

Reputation: 54433

Update: I misread your question and thought you want a 'stable' sort. For this you would need to use LINQ in one way or another.

But you always want the Name column sorted ascending; this can be done by coding the SortCompare event, maybe like this:

private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    if (e.CellValue1 == e.CellValue2)
    {
        int order = dataGridView1.SortOrder == SortOrder.Ascending ? 1 : -1;
        string altCol = "Name";
        if (e.Column.Name == "Name")  altCol = "Status";

        string s1 = dataGridView1[altCol, e.RowIndex1].Value.ToString();
        string s2 = dataGridView1[altCol, e.RowIndex2].Value.ToString();
        e.SortResult = String.Compare(s1, s2) * order;
        e.Handled = true;
    }
}

I test to see for equality on the main sort column. Only then we need to intervene and switch to the altenate sort column. I use your two column names hard coded..

I use the variable order to correct the unwanted reversal that would happen for descending sorts.

For the sort to work you need to set each column's SortMode somewhere:

foreach (DataGridViewColumn col in dataGridView1.Columns) 
         col.SortMode = DataGridViewColumnSortMode.Automatic;

Upvotes: 2

Binesh Nambiar C
Binesh Nambiar C

Reputation: 162

I don't know datagridview much.

but able to see a specification in microsoft like there is a IComparer overload for sort method

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.sort(v=vs.110).aspx

I think you can programically atleast do your requirement by implementing the interface.

See for sample

http://msdn.microsoft.com/en-us/library/wstxtkxs%28v=vs.110%29.aspx

Upvotes: 0

Casey
Casey

Reputation: 335

Sort operations do not work independently on columns. The data in the row stays with its identity.

Upvotes: 1

Related Questions