[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 513
  • Last Modified:

GridView_Sorting and tying to DataSource

How do I do the following ? thanks - I am lost!!
       
            myGridView.DataSource = Access_Data_Source1;   ???? how? I want the following routine to work correctly. thanks.

    protected void myGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            AccessDataSource Access_Data_Source1 = new AccessDataSource(
    "~/App_Data/AccountInfo_Nov14_2009.mdb", "Select * from AceData");
 
           Access_Data_Source1 .DefaultView.Sort = e.SortExpression + "  " + GetSortDirection(e.SortExpression);
              Access_Data_Source1.DefaultView.Sort = e.SortExpression + "  " + GetSortDirection(e.SortExpression);


            myGridView.DataSource = Access_Data_Source1;

    //        myGridView.DataSource = dt;
            myGridView.DataBind();

        }

        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";
                    }
                }
            }

            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }
0
goodk
Asked:
goodk
  • 12
  • 7
1 Solution
 
goodkAuthor Commented:
waiting...
0
 
goodkAuthor Commented:
Do we have anyone who can answer??????/

I am waiting,

All I want to know is how to handle sorting in Gridview control?  Please thanks!

I am using MSAccess!
0
 
goodkAuthor Commented:
I am getting error at this line,
Access_Data_Source1 .DefaultView.Sort = e.SortExpression + "  " + GetSortDirection(e.SortExpression);
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
goodkAuthor Commented:
I followed another example, but I am still getting an error!!
             DataTable sourceTable = GridAttendence.DataSource as DataTable;
            DataView view = new DataView(sourceTable);


       protected void myGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            AccessDataSource Access_Data_Source1 = new AccessDataSource(
    "~/App_Data/AccountInfo_Nov14_2009.mdb", "Select * from AceData");
   //         DataTable dt;
   //         dt = Data();
            DataTable sourceTable = GridAttendence.DataSource as DataTable;
            DataView view = new DataView(sourceTable);
 
           
            //       dt.DefaultView.Sort = e.SortExpression + "  " + GetSortDirection(e.SortExpression);
              myGridView.Sort =e.SortExpression + "  " + GetSortDirection(e.SortExpression);


            myGridView.DataSource = Access_Data_Source1;

    //        myGridView.DataSource = dt;
            myGridView.DataBind();

        }
0
 
ROMA CHAUHANProject LeadCommented:
have u tried ...

dt.DefaultView.Sort = "fieldname desc";
0
 
ROMA CHAUHANProject LeadCommented:
If you are using asp.net then datagrid itself has property AllowSorting. Make it True.
0
 
goodkAuthor Commented:
DataTable sourceTable = myGridView.DataSource as DataTable;
            DataView view = new DataView(sourceTable);

The word DataTable is not recognized by the compiler

Here is the whole code, everything is working except Sorting!! Please help!

<%@ Page AutoEventWireup="true" Culture="auto" ErrorPage="~/Prod/Problem.htm" Language="C#"
    MasterPageFile="~/MasterPage.master" Theme="GridView" Title="Sure Accounting" UICulture="auto" %>
   


<script runat="server">
   



   

   
   
    void Page_Load()
    {
        myGridView.PageIndexChanging += myGridView_PageIndexChanging;
       myGridView.Sorting += myGridView_Sorting;

        if (IsPostBack)
       {
            Session.Add("PageName", "AnyTable");
       }
       else
       {
              SetSQLOnChange("PostBack");
           
      }

    }

    protected void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        myGridView.PageIndex = e.NewPageIndex;
        //myGridView.DataSource = Data();
        AccessDataSource Access_Data_Source1 = new AccessDataSource(
"~/App_Data/AccountInfo_Nov14_2009.mdb", "Select * from AceData");

        myGridView.DataSource = Access_Data_Source1;
        myGridView.DataBind();
    }
   
   
   
   
   
   
   
   
   
        protected void myGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            AccessDataSource Access_Data_Source1 = new AccessDataSource(
    "~/App_Data/AccountInfo_Nov14_2009.mdb", "Select * from AceData");
   //         DataTable dt;
   //         dt = Data();
            DataTable sourceTable = myGridView.DataSource as DataTable;
            DataView view = new DataView(sourceTable);


            DataView.DefaultView.Sort = e.SortExpression + "  " + GetSortDirection(e.SortExpression);
            //  myGridView.Sort =e.SortExpression + "  " + GetSortDirection(e.SortExpression);


            myGridView.DataSource = Access_Data_Source1;

    //        myGridView.DataSource = dt;
            myGridView.DataBind();

        }

        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";
                    }
                }
            }

            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

    void SetSQLOnChange(string xPostBack)
    {
       // Response.Write("   In SetSQLOnChange tempStringSelected   " + tempStringSelected);
       // AccessDataSource xAccountDataSource = new AccessDataSource();
        string connString = AceClasses.GetConnString();

       
       

        AccessDataSource Access_Data_Source1 = new AccessDataSource(
"~/App_Data/AccountInfo_Nov14_2009.mdb","Select * from AceData");
       
        // Create a new GridView object.
     //   GridView myGridView = new GridView();

        // Set the GridView object's properties.

     //   myGridView.ID = "myGridView";
      //  myGridView.DataSource = SqlDS;
    //    myGridView.DataSource = AccessDS;
         myGridView.DataSource = Access_Data_Source1;
      // myGridView.SkinID = "gvSkinId";
       
       myGridView.AutoGenerateColumns = false;


       myGridView.Columns.Add(CodeClass.CreateBoundField("Description", "Description", " Description ", "", ""));
       myGridView.Columns.Add(CodeClass.CreateBoundField("Date", "Date", " Date ", "datetime", ""));
        myGridView.Columns.Add(CodeClass.CreateBoundField("Type", "Type", " Type ", "", ""));
        myGridView.Columns.Add(CodeClass.CreateBoundField("Job", "Job", " Job ", "", ""));
      myGridView.Columns.Add(CodeClass.CreateBoundField("InCredit", "InCredit", " InCredit ", "money", ""));
       myGridView.Columns.Add(CodeClass.CreateBoundField("OutDebit", "OutDebit", " OutDebit ", "money", ""));
        myGridView.Columns.Add(CodeClass.CreateBoundField("FinancialEntity", "FinancialEntity", " FinancialEntity ", "", ""));

             
        //newBoundField.NavigateUrl = "Default.aspx";
        // Add the GridView object to the Controls collection
        // of the PlaceHolder control.
      //  GridViewPlaceHolder.Controls.Add(myGridView);
        myGridView.DataBind();

    }


       

</script>



<asp:Content ID="Content1" runat="Server" ContentPlaceHolderID="ContentPlaceHolder1">





   <div>
 
    <asp:SqlDataSource
    id="SqlDS"
    runat="server"     />

       <asp:AccessDataSource ID="AccessDS" runat="server"></asp:AccessDataSource>
     
       <asp:GridView ID="myGridView" AllowSorting = "true" AllowPaging = "true" runat="server">
       </asp:GridView>
 
   </div>
   
</asp:Content>


0
 
ROMA CHAUHANProject LeadCommented:
for datatable have u import the library for that.
At the top of the code...
using System.Data;
0
 
goodkAuthor Commented:
that worked;
           DataTable sourceTable = myGridView.DataSource as DataTable;
            DataView view = new DataView(sourceTable);


Now getting stuck at the following line;
            DataTable.DefaultView.Sort = e.SortExpression + "  " + GetSortDirection(e.SortExpression);
0
 
ROMA CHAUHANProject LeadCommented:
you don't have to write DataTable.DefaultView.Sort .
Instead of DataTable use the sourceTable .DefaultView.Sort
0
 
goodkAuthor Commented:
thanks, Now I am getting the following error -

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.



NullReferenceException: Object reference not set to an instance of an object.]
   ASP.examples_copyanytable_aspx.myGridView_Sorting(Object sender, GridViewSortEventArgs e) +91
   System.Web.UI.WebControls.GridView.OnSorting(GridViewSortEventArgs e) +133
   System.Web.UI.WebControls.GridView.HandleSort(String sortExpression, SortDirection sortDirection) +78
   System.Web.UI.WebControls.GridView.HandleSort(String sortExpression) +75
   System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +531
   System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +207
   System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565


        protected void myGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            AccessDataSource Access_Data_Source1 = new AccessDataSource(
    "~/App_Data/AccountInfo_Nov14_2009.mdb", "Select * from AceData");
   //         DataTable dt;
   //         dt = Data();
            DataTable sourceTable = myGridView.DataSource as DataTable;
            DataView view = new DataView(sourceTable);


            sourceTable.DefaultView.Sort = e.SortExpression + "  " + GetSortDirection(e.SortExpression);
            //  myGridView.Sort =e.SortExpression + "  " + GetSortDirection(e.SortExpression);


            myGridView.DataSource = Access_Data_Source1;

    //        myGridView.DataSource = dt;
            myGridView.DataBind();

        }

        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";
                    }
                }
            }

            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }
0
 
ROMA CHAUHANProject LeadCommented:
You must have to create the object of class before calling the class method.
Like........
        AceClasses objAceClasses = new AceClasses();
        objAceClasses.GetConnString();


        CodeClass objCodeClass = new CodeClass();
        myGridView.Columns.Add(objCodeClass.CreateBoundField("Description", "Description", " Description ", "", ""));
0
 
goodkAuthor Commented:
Sorry, that is not a problem.  The fields displays just fine.  The error occurs when I clicked the Field Name to sort the field.

Pagination is also working fine.  

Stack is also pointing to the sort
 System.Web.UI.WebControls.GridView.HandleSort(String sortExpression) +75
0
 
goodkAuthor Commented:
This may be a clue to the poblem - please help - thanks
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
0
 
goodkAuthor Commented:
Can you kindly fix the sort routine, rest is working fine. thanks
0
 
ROMA CHAUHANProject LeadCommented:
i m not able to understand what is the problem in inbuilt sorting propety available in datagridview?
u can use it no need to code for that.
0
 
ROMA CHAUHANProject LeadCommented:
Ok. I get the problem. If you keep the breakpoint over there, you'll get null as that datatable. Because you are not getting anything in datatable and trying to sort the null data thats why giving you the error of object reference not set.

Better to use oleDbDataconnection instead of AccessDataSource. I m giving u the tested running code same as yours but oledb instead of AccessDataSource. Try this.
Simple, easy and efficient code.....
Content page designer.......
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
  <asp:GridView ID="myGridView" AllowSorting="true" AllowPaging="true" runat="server" PageSize="2" OnPageIndexChanging="myGridView_PageIndexChanging" OnSorting="myGridView_Sorting">
        </asp:GridView>
             <asp:AccessDataSource ID="AccessDS" runat="server"></asp:AccessDataSource>
</asp:Content>

//Source Code
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.OleDb;
public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetDataInGridFromAccess();
        }
    }
    protected void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        myGridView.PageIndex = e.NewPageIndex;
        myGridView.DataSource = (DataTable)ViewState["GridData"];
        myGridView.DataBind();
    }
    protected void myGridView_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable sourceTable = new DataTable();
        sourceTable = (DataTable)ViewState["GridData"];
        sourceTable.DefaultView.Sort = e.SortExpression + "  " + GetSortDirection(e.SortExpression);
        myGridView.DataSource = sourceTable;
        myGridView.DataBind();
    }
    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";
                }
            }
        }
        ViewState["SortDirection"] = sortDirection;
        ViewState["SortExpression"] = column;
        return sortDirection;
    }
    void GetDataInGridFromAccess()
    {
        OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/app_data/AccountInfo_Nov14_2009.mdb"));
        OleDbDataAdapter adpt = new OleDbDataAdapter("select * from AceData", cn);
        DataTable dt = new DataTable("dtAceData");
        adpt.Fill(dt);
        adpt.Dispose();
        myGridView.DataSource = dt;
        myGridView.DataBind();
        ViewState["GridData"] = dt;
    }

   
}

Open in new window

0
 
goodkAuthor Commented:
It worked like a charm! Thanks!  

Just one observation that the response is slow when flipping pages or sorting.  I am wondering why other way was faster?

thanks anyway! It took time but you finally did it!! thanks for your persistance.
0
 
goodkAuthor Commented:
Well, after the page is sorted, and when pages are flipped, it does not preserve the sort order.
 
 
 
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 12
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now