Custom sorting by DataGridView

I found several questions similar to this here on SO, but none of them matched this issue, so we go.

I have a DataGridView showing team members. All team members have an assigned role in the team, indicated in one of the columns. Examples might be Legal Representative, Account Manager, Assistant Account Manager, or Accountant.

Now that gets interesting. I basically want to sort the grid on this column alphabetically, except for a few. "Account Manager" should always be listed at the top, followed by "Account Manager Assistant" if available.

The objects and mesh are working at this stage and have been in production for a while now, so I don't want to do more work on this than is necessary.

Is there an easy way to do this? I guess I have to do it programmatically ...

Some pseudocode to clarify:

if (memberRole == 'Account Manager') 
{
    //put in top row
}
else if (memberRole == 'Assistant Account Manager')
{
    //put in second row 
}
else
{
    //sort remaining rows alphabetically
}

      

I am doing my job in C # .NET using Visual Studio 2008.

+2


source to share


3 answers


You can capture the SortCompare event of your datagridview document:



    private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        string cell1, cell2;

        if (e.Column == "Your_Column")
        {
            if (e.CellValue1 == null) cell1 = "";
            else cell1 = e.CellValue1.ToString();

            if (e.CellValue2 == null) cell2 = "";
            else cell2 = e.CellValue2.ToString();

            if (cell1 == "Account Manager") { e.SortResult = -1; e.Handled = true; }
            else
            {
                if (cell2 == "Account Manager") { e.SortResult = 1; e.Handled = true; }
                else
                {
                    if (cell1 == "Assistant Account Manager") { e.SortResult = -1; e.Handled = true; }
                    else
                    {
                        if (cell2 == "Assistant Account Manager") { e.SortResult = 1; e.Handled = true; }
                    }
                }
            }
        }
    }

      

+2


source


Or, when getting data from the server side, you can sort it and then push it to the front via w / e json etc., so the whole list shows the data and the data is sorted on the server



0


source


Another solution, which some may not like, but is quickly implemented and works well, is to introduce a new object property for sorting. The make new property contains the collation as the first character (number works well) and the actual collation as the rest of the characters. Implement some light if-else statements to set the appropriate value for the sort property.

When adding this column to the grid, just make it hidden and sort by that column.

Possibly less elegant solution than the one suggested by najmeddine, but it works.

0


source







All Articles