views:

746

answers:

2

When i try to sort my table manually, i receive this error: DataTable must be set prior to using DataView. The code is:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {

        DataTable sourceTable = GridView1.DataSource as DataTable;
        DataView view = new DataView(sourceTable);
        string[] sortData = Session["sortExpression"]!= null ? Session["sortExpression"].ToString().Trim().Split(' ') : null;
        if (sortData != null && e.SortExpression == sortData[0])
        {
            if (sortData[1] == "ASC")
            {
                view.Sort = e.SortExpression + " " + "DESC";
                Session["sortExpression"] = e.SortExpression + " " + "DESC";
            }
            else
            {
                view.Sort = e.SortExpression + " " + "ASC";
                Session["sortExpression"] = e.SortExpression + " " + "ASC";
            }
        }
        else
        {
            view.Sort = e.SortExpression + " " + "ASC";
            Session["sortExpression"] = e.SortExpression + " " + "ASC";
        }

    }

Where i wrong?

A: 

It's possible your datatable also needs to be part of a dataset.

Similar to

DataSet ds = new DataSet()
DataTable sourceTable = GridView1.DataSource as DataTable;
ds.Tables.Add(sourceTable)
DataView view = new DataView(sourceTable);
string[] sortData = Session["sortExpression"]!= null ? Session["sortExpression"].ToString().Trim().Split(' ') : null;

This is only from weird past experience

Robert
A: 

Most likely GridView1.DataSource is null. You can find a tutorial on Gridview sorting here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx

edosoft