Click here to Skip to main content
15,903,175 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I have a grid view and i need to sort the columns on clicking the column headers.. this is the code for binding to gridview and code gor sorting..

C#
private void BindData()
{
    string strQuery = "select Employee_ID as ID,Employee_Name as Name,Employee_Address as Address,Employee_Email as Email,Employee_Department as Department from ISSSignUp";
    try
    {
        SqlConObject.Open();
        SqlCommand sqlcommandobject = new SqlCommand(strQuery, SqlConObject);
        SqlDataReader sqldatareaderobject = sqlcommandobject.ExecuteReader();
        gridRegistrationTableDetails.DataSource = sqldatareaderobject;
        gridRegistrationTableDetails.DataBind();
    }
    catch (Exception e5)
    {
        lblError.Text = e5.Message;
    }

    finally
    {
        SqlConObject.Close();
    }
}


code for sorting is

C#
protected void SortingGridData(object sender, GridViewSortEventArgs e)
   {
       string sortingDirection = string.Empty;
       if (SortDir == SortDirection.Ascending)
       {
           SortDir = SortDirection.Descending;
           sortingDirection = "Desc";
       }
       else
       {
           SortDir = SortDirection.Ascending;
           sortingDirection = "Asc";
       }


       DataView sortedView = new DataView();
       BindData();
       sortedView.Sort = e.SortExpression + " " + sortingDirection;
       gridRegistrationTableDetails.DataSource = sortedView;
       gridRegistrationTableDetails.DataBind();

   }

   public SortDirection SortDir
   {
       get
       {
           if (ViewState["SortDirection"] == null)
           {
               ViewState["SortDirection"] = SortDirection.Ascending;
           }
           return (SortDirection)ViewState["SortDirection"];
       }
       set
       {
           ViewState["SortDirection"] = value;
       }
   }


I have written the above code somewhat by googling on various sites and referring then.I get this error
""DataTable must be set prior to using DataView.""
help me friends and give me the correct code.. thanks in advance..
Posted
Updated 5-Aug-12 21:15pm
v2
Comments
Unareshraju 6-Aug-12 4:47am    
hi ajith why don't you sorting rows in storeprocedure also. through the code some more complex. just use a Desc function in storeprocedure that's all.

Column names should not have spaces in between words to be sorted. Cannot sort colum name "Product Name" should be either "Product_Name" or in definition of fields you should put:
SortExpression="ProductName"

without spaces, like:
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName"/>


If there is space he will use only first bit and not recognise column at all.

Dali
 
Share this answer
 
Comments
CHill60 4-Jun-13 10:09am    
This post is nearly a year old and already had 5 solutions posted
Dali Golub 4-Jun-13 11:29am    
Although it is one year old and have 5 solutions, I did not find any of them answering why there is error for not existing column. I was looking for answer myself just yesterday and today and I figure out by testing that mistake is in spaces between words, so I went and leave comment as I know that will help others who were stuck as I was.
Bind your Gridview using Datatable..


Thanks
Ashish
 
Share this answer
 
Hi,
I could have written the code which can solve you problem, but I would like to suggest you to read GridView Paging and Sorting[^]. This is a very nice article for the beginners.



--Amit
 
Share this answer
 
You need to set the DataView with DataTable and then you will be able to sort your gridview.
See below example:
http://stackoverflow.com/questions/3966835/sorting-gridview[^]
 
Share this answer
 
In your binddata method, create a new datatable and dump sqldatareader to datatable:

  private void BindData()
    {
        string strQuery = "select Employee_ID as ID,Employee_Name as Name,Employee_Address as Address,Employee_Email as Email,Employee_Department as Department from ISSSignUp";
        try
        {
            SqlConObject.Open();
            SqlCommand sqlcommandobject = new SqlCommand(strQuery, SqlConObject);
            SqlDataReader sqldatareaderobject = sqlcommandobject.ExecuteReader();
            gridRegistrationTableDetails.DataSource = sqldatareaderobject;
            gridRegistrationTableDetails.DataBind();
DataTable dt = new DataTable();
dt = sqldatareaderobject.GetSchemaTable();
Session["Datatable"]=dt;
        }
        catch (Exception e5)
        {
            lblError.Text = e5.Message;
        }
 
        finally
        {
            SqlConObject.Close();
        }
    }



Then in sorting griddata, get the session object back to datatable and pass it to dataview.
DataTable dt=Session["DataTable"] as DataTable;
        DataView sortedView = new DataView(dt);
        BindData();
        sortedView.Sort = e.SortExpression + " " + sortingDirection;
        gridRegistrationTableDetails.DataSource = sortedView;
        gridRegistrationTableDetails.DataBind();
 
Share this answer
 
v2
Comments
ajithk444 6-Aug-12 3:50am    
what is "sd" in dt=sd.DetSchemaTable();
Santhosh Kumar Jayaraman 6-Aug-12 3:52am    
that should be sqldatareaderobject ....Updated the solution.
ajithk444 6-Aug-12 3:56am    
I get the error as "Cannot find column Name."
in this line. "sortedView.Sort = e.SortExpression + " " + sortingDirection;"
what is my problem
Santhosh Kumar Jayaraman 6-Aug-12 3:59am    
checkmy code, How i have handled. its difficult to know where it goes wrong without debuggin applicatiom.



My aspx.cs code bhind for sorting

Collapse | Copy Code

protected void GridView_Result_Sorting(object sender, GridViewSortEventArgs e)
{
ViewState["sortexp"] = e.SortExpression;
GridView_Result.DataSource = binddata("sort");
GridView_Result.DataBind();
}



Then my methods:

Collapse | Copy Code

private string GetSortDirection(string column)
{
string sortDirection = "ASC";
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}

// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;

return sortDirection;
}


private DataView binddata(string mode)
{

dataView = Session["DataView"] as DataView;
if (mode == "sort")
{
if (ViewState["sortexp"] != null)
{
dataView.Sort = (string)ViewState["sortexp"] + " " + GetSortDirection((string)ViewState["sortexp"]);
}
}
return dataView;
}
ajithk444 6-Aug-12 4:05am    
I cant get wat s wrong for invalid column error in my application...shall i give my whole code. can you help me out..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900