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

前端 未结 1 1183
春和景丽
春和景丽 2020-12-11 12:04

I want to convert my GridView to a DataTable. Note: The GridView doesn\'t have a DataSource! I want to sort the DataTable and put it back to the GridView, is it possible? Im

相关标签:
1条回答
  • 2020-12-11 12:50

    Put your DataTable in a ViewState when you bind for the first time.

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

    and then do like...

    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 take a look at this MSDN article http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx

    0 讨论(0)
提交回复
热议问题