How to convert a GridView to a DataTable and sort a DataTable?

I want to convert my GridView to a DataTable. Note. GridView missing DataSource! I want to sort the DataTable and return it to the GridView, is this possible? The important thing is that my GridView should be sorted.

Thanks in advance.

+2
source share
1 answer

Put yours DataTablein ViewStatewhen you get attached for the first time.

gridView1.DataBind();
ViewState["dtbl"] = YourDataTable

and then do ...

protected void ComponentGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    DataTable dataTable = ViewState["dtbl"] as DataTable;

    if (dataTable != null)
    {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);

        ComponentGridView.DataSource = dataView;
        ComponentGridView.DataBind();
    }
}

private string ConvertSortDirection(SortDirection sortDirection)
{
    string newSortDirection = String.Empty;

    switch (sortDirection)
    {
        case SortDirection.Ascending:
            newSortDirection = "ASC";
            break;

        case SortDirection.Descending:
            newSortDirection = "DESC";
            break;
    }

    return newSortDirection;
}

Also check out this MSDN article http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx

+3
source

All Articles