开发者

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

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? Important is that my GridView must be sorted.

Thank you in advance开发者_运维知识库.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜