Sorting by clicking column returns back all columns in C#

291 Views Asked by At

I have a gridview table that has auto generated columns and the rows in those columns can be sorted by clicking the column name since I have "AllowSorting" on. I also have checkbox lists that the user can check or uncheck to filter columns in and out of the table.

The problem is when the user filters the table to whatever columns they want and then they click on any column name, it will sort by that column but it brings back all of the columns that they filtered out.

I am guessing that I need to create a class with GridViewSortEventArgs and make the event grab only the columns the user filters instead of selecting all the columns in the database. I tried this but I don't know if I'm headed in the right direction or not but I also do get an error on GetSortColumnIndex() saying "not all code paths return a value". SQLQueryBuilder() obviously builds the query for the table btw.

private void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        int sortColumnIndex = GetSortColumnIndex();

        if (sortColumnIndex != -1)

            SQLQueryBuilder();

    }

    int GetSortColumnIndex()
    {
        foreach (DataControlField field in GridView1.Columns)
        {
            if (field.SortExpression == GridView1.SortExpression)
            {
                return GridView1.Columns.IndexOf(field);
            }
        }
    }
1

There are 1 best solutions below

1
On

not all code paths return a value

int GetSortColumnIndex()
{
    foreach (DataControlField field in GridView1.Columns)
    {
        if (field.SortExpression == GridView1.SortExpression)
        {
            return GridView1.Columns.IndexOf(field);
        }
    }
}

You only return a value if field.SortExpression == GridView1.SortExpression, so add a return -1; at the end of your method.

As for the filtered values problem, do you account for the filtering in

SQLQueryBuilder();

My guess is you're rebuilding the query from scratch there.