HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

Rate It (26)

Last post 07-30-2007 2:56 AM by krishanmanral. 185 replies.

Sort Posts:

  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    10-28-2006, 1:22 PM
    Locked

    Now I have a new problem, that I don't know how to solve it!

    I have a gridview in wich I use the paging/sorting code, and in each row I have a select column so I can retrive one of the fields.

    The code that I use to do it is:

     

        Protected Sub gvSupplier_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvSupplier.SelectedIndexChanged
            Dim keys As DataKey
            Dim i As Integer = Me.gvSupplier.SelectedIndex
    
            Me.txtSupplier.Text = Trim(Me.gvSupplier.SelectedValue.ToString())
    
            keys = Me.gvSupplier.DataKeys(i)
            For Each d As DictionaryEntry In keys.Values
                If d.Key = "ID" Then
                    Me.hfID_Supplier.Value = d.Value
                End If
            Next
    
            Me.gvSupplier.Visible = False
        End Sub
    

      The problem is that when I use the sorting, the selectindex that I retrieve is not from the sorted gridview.

    How can I retrieve the right one????

    Thank's

    Paula 

  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-01-2006, 3:13 PM
    Locked
    • Member
      5 point Member
    • captain1210
    • Member since 11-01-2006, 8:06 PM
    • Posts 6

    Hi first I want say thank you for you help, I've been searching for days to assist me on doing my grid. I have 1 little issue. I keep getting this error msg

    "Unable to cast object of type 'System.Data.DataView' to type 'System.Data.DataTable'. " on this line "GridViewTransHist.DataSource = SortDataTable(GridViewTransHist.DataSource, False)". What am I doing wrong?

    my code below.


    Partial Class _Default
        Inherits System.Web.UI.Page

        Dim sqlConn As Data.SqlClient.SqlConnection = New _
        Data.SqlClient.SqlConnection("Data Source=CCBLOANDATA\DEVELOPMENT;Initial Catalog=LoanRev;Integrated Security=True")


        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            'setup transaction type dropdownlist box
            Dim cmdSqlTransType As Data.SqlClient.SqlCommand = New _
            Data.SqlClient.SqlCommand("select txn_cde, (txn_cde + ': ' + isnull(trans_function,'<Unknown description>')) as trans_function " & _
            "from v_alldaytxn group by txn_cde, trans_function order by txn_cde", sqlConn)
            sqlConn.Open()
            drpdwnTransCode.DataSource = cmdSqlTransType.ExecuteReader()
            drpdwnTransCode.DataTextField = "trans_function"
            drpdwnTransCode.DataValueField = "txn_cde"
            'dont want the DropDownList to load again

            If Not IsPostBack Then
                drpdwnTransCode.DataBind()
                drpdwnTransCode.Items.Insert(0, "ALL")


            End If
            sqlConn.Close()


        End Sub

        Protected Sub btnGetData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetData.Click
            PopulateTransHistGrid()
        End Sub
        Private Sub PopulateTransHistGrid()

            Dim sqlwhere As String
            Dim gridquery As String
            If drpdwnTransCode.Text = "ALL" Then
                sqlwhere = " "
            Else
                sqlwhere = " txn_cde = " & drpdwnTransCode.Text & " AND "
            End If

            sqlwhere = sqlwhere & " txn_eff_dt <= '" & txtenddt.SelectedDateFormatted & "'" & _
            " AND txn_eff_dt >= '" & txtbegdt.SelectedDateFormatted & "'"

            gridquery = "SELECT Escr_amt, escr_res_amt, Int_amt, late_chg_amt, " & _
            "Principal, unapplied_amt, txn_cde, is_cash_trans, acct_nbr, " & _
            "cash_trans_type, trans_function, CONVERT(char(10), txn_eff_dt, 101) as txn_eff_dt, txn_amt " & _
            "FROM v_alldaytxn where " & sqlwhere & " order by txn_eff_dt desc"

            sqlConn.Open()
            Dim dsTranHist As Data.DataSet
            Dim cmdTranHist As Data.SqlClient.SqlDataAdapter
            cmdTranHist = New Data.SqlClient.SqlDataAdapter(gridquery, sqlConn)
            dsTranHist = New Data.DataSet()
            cmdTranHist.Fill(dsTranHist, "v_alldaytxn")
            Dim dataTableRowCount As Integer = GridViewTransHist.Rows.Count

            'If dataTableRowCount > 0 Then
            GridViewTransHist.DataSource = dsTranHist.Tables("v_alldaytxn").DefaultView
            GridViewTransHist.DataBind()
            sqlConn.Close()
            'End If

        End Sub


        Protected Sub GridViewTransHist_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridViewTransHist.PageIndexChanging

            GridViewTransHist.DataSource = SortDataTable(GridViewTransHist.DataSource, True)
            GridViewTransHist.PageIndex = e.NewPageIndex
            GridViewTransHist.DataBind()

        End Sub
        Private Property GridViewSortDirection() As String

            Get
                Return IIf(ViewState("SortDirection") = Nothing, "ASC", ViewState("SortDirection"))
            End Get

            Set(ByVal value As String)
                ViewState("SortDirection") = value
            End Set

        End Property
        Private Property GridViewSortBLOCKED EXPRESSION As String

            Get
                Return IIf(ViewState("SortExpression") = Nothing, String.Empty, ViewState("SortExpression"))
            End Get

            Set(ByVal value As String)
                ViewState("SortExpression") = value
            End Set

        End Property
        Private Function GetSortDirection() As String

            Select Case GridViewSortDirection
                Case "ASC"
                    GridViewSortDirection = "DESC"
                Case "DESC"
                    GridViewSortDirection = "ASC"
            End Select

            Return GridViewSortDirection

        End Function

     

        Protected Function SortDataTable(ByVal dataTable As Data.DataTable, ByVal isPageIndexChanging As Boolean) As Data.DataView

            If Not dataTable Is Nothing Then
                Dim dataView As New Data.DataView(dataTable)

                If GridViewSortExpression <> String.Empty Then
                    If isPageIndexChanging Then
                        dataView.Sort = String.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection)
                    Else
                        dataView.Sort = String.Format("{0} {1}", GridViewSortExpression, GetSortDirection())
                    End If
                End If

                Return dataView
            Else
                Return New Data.DataView()
            End If

        End Function

        Protected Sub GridViewTransHist_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridViewTransHist.Sorting

            GridViewSortExpression = e.SortExpression
            Dim pageIndex As Integer = GridViewTransHist.PageIndex
            GridViewTransHist.DataSource = SortDataTable(GridViewTransHist.DataSource, False)
            GridViewTransHist.DataBind()
            GridViewTransHist.PageIndex = pageIndex

        End Sub
    End Class

  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-06-2006, 12:22 PM
    Locked
    • Member
      70 point Member
    • aKa Davi
    • Member since 11-05-2006, 7:45 AM
    • Posts 14

    Hi, The above Paging code works fine, im using an oracle stored procedure, bidning it to a gridview.

    However, i also have a 'user filter' where teh user can filter the records by entering data to filter by.

    The problem is that the paging works, but when you click to see the next page, the fliter paramters are reset.

    The flitering works by simply passing the values of the filter controls to the oracle stored procedure which returns data depending on those values.

    Can anyone help? 

    -Dave
  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-06-2006, 3:15 PM
    Locked

    Hello captain1210

    I'm not a expert, but I think that your problem is that you are using a dataset instead of a datatable.

    Look at the code that I use, and it's working:

            sqlConn = New SqlConnection(...)
            Dim strsql As String = "..."

            Dim da As New SqlDataAdapter(strsql, sqlConn)
            Dim ds As New DataTable
            da.Fill(ds)

            Me.gvSign.DataSource = ds
            Me.gvSign.DataBind()

     I hope that's what you need.

    Paula
     

     

  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-06-2006, 3:45 PM
    Locked
    • Member
      254 point Member
    • maniac
    • Member since 12-29-2005, 4:15 PM
    • Posts 92
    • If you're using .net 2.0, go with auto-generate fields & GridView.
      • I am wrapping up final functionality with it.
        • It's exactly like the DataGrid, but with way less code.
    A+ BS MCSE OOP Security+ Web Developer
    Get creative, not even.
  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-08-2006, 3:20 PM
    Locked
    • Member
      15 point Member
    • user_one
    • Member since 11-02-2006, 5:00 PM
    • Posts 42
    Hello,
    I'm also trying to implement 'custom' paging, in ASP.NET 2.0 using GridView WITHOUT using objectdatasource.
    The approach oulined above is not scalable. It retrieves ALL records. Custom paging should use database stored procdure to fetch only the records of the current page.
    How can that 'custom' paging be implemented (WITHOUT using objectdatasource) ?
  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-08-2006, 4:39 PM
    Locked
    • All-Star
      30,698 point All-Star
    • StrongTypes
    • Member since 12-13-2005, 4:21 PM
    • California
    • Posts 6,007
    • ASPInsiders
      Moderator
      TrustedFriends-MVPs

    user_one:
    Hello,
    I'm also trying to implement 'custom' paging, in ASP.NET 2.0 using GridView WITHOUT using objectdatasource.
    The approach oulined above is not scalable. It retrieves ALL records. Custom paging should use database stored procdure to fetch only the records of the current page.
    How can that 'custom' paging be implemented (WITHOUT using objectdatasource) ?

    The code in this post is aimed at those who need help enabling sorting/paging without a DataSourceControl, not advanced techniques. If you're not satisfied with that, I invite you to modify the code as you are expecting it to function.

  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-09-2006, 9:12 AM
    Locked
    • Member
      254 point Member
    • maniac
    • Member since 12-29-2005, 4:15 PM
    • Posts 92

    user_one:

    • sp is the way to go.
      • It retrieves exactly what you need because the sqlDataSource can only do simple queries (e.g. 1 table only ... LOL).
      • I had to add a HyperLinkField to call custom code for a custom view, works like a charm.
    • Per custom paging, check out prior reply that commences with "I think I'm almost there... I hope!"

    Ryan:

    • Kudos ... great thread ... found a more efficient solution thanx to you!

    : )

    A+ BS MCSE OOP Security+ Web Developer
    Get creative, not even.
  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-09-2006, 3:39 PM
    Locked
    • Member
      17 point Member
    • Bouha
    • Member since 11-09-2006, 8:18 PM
    • Posts 4

    hi!

    i'm trying to make a class which will manage different pages containing diffrent gridviews. i'm using the methods described here but i have a big problem.

    i can't catch the gridview events in the class, say it's PagingSorting class, i instantiate this class in the page load then i put it in a session variable and then in the post back i unbox it again. i do have methods on it that adds the handler to the  sorting event of the grid for example,  but this event is not fired, i do add the handler on both, the postback and in the first load of the page but the event doesn't get fired.

    i searched a lot and i found that, if the method in which i add the handler for the gridview event was put static and inside it i do like that :

    GV.sorting += delegate{ do something.....}

    then the event get fired and handled but that doesn't suit me because i need the eventargs for the sorting event to take the sortexpression etc....

    so when i change to GV.sorting += new Eventhandler(SortingMethod)  that doesn't work.

    so i think my problem can be resumed by the fact that i need to handle an event of a web control in a page in a different class and in the same time when handling the event having access to the event args.

    sorry for my english 

    i hope u did understood me 

     thx in advance

  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    11-10-2006, 11:20 AM
    Locked
    • Member
      17 point Member
    • Bouha
    • Member since 11-09-2006, 8:18 PM
    • Posts 4

    hi again !

    i finally i gave up i didn't find anyway to do it apart to instantiate always the class ine the pageload, that's said it works very good but i think it's not optimized because of the problem i mentioned earlier.

    thx again! 

  • Handling exception

    11-10-2006, 4:45 PM
    Locked
    • Member
      95 point Member
    • aspnet_spnt
    • Member since 08-28-2006, 4:22 PM
    • Posts 19

    Iam trying to give access to users who are in a database table the code is working fine if i type in the right username and password. But when i type incorrect username or password iam getting an error: index out of range exception was not handled by user code. There is no row at position 0.Blow is the code which iam using for authentication and iam using OLEDB connection.


     sql query = new sql();
    DataTable dt = query.queryDbReturnDt("SELECT PER_ID,VARIABLE_NAME,VARIABLE_VALUE FROM LOGIN WHERE (PER_ID='" + id + "') AND (VARIABLE_NAME='PASS')AND (VARIABLE_VALUE = '" + password + "')", ref lblerror);

    if (id == dt.Rows[0]["PER_ID"].ToString() && password == dt.Rows[0]["VARIABLE_VALUE"].ToString()))
                {
              FormsAuthentication.SetAuthCookie(id, false);
                    Response.Redirect(@"~/temp.aspx");
                }

    What should i do now??

  • Re: Handling exception

    12-14-2006, 4:36 PM
    Locked
    • Member
      310 point Member
    • sduffy
    • Member since 05-25-2005, 2:50 PM
    • Posts 68
    Thanks for the great post, saved me a ton of time.
    - Shaun
  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    12-15-2006, 8:58 AM
    Locked
    • Member
      310 point Member
    • sduffy
    • Member since 05-25-2005, 2:50 PM
    • Posts 68
    StrongTypes:

    user_one:
    Hello,
    I'm also trying to implement 'custom' paging, in ASP.NET 2.0 using GridView WITHOUT using objectdatasource.
    The approach oulined above is not scalable. It retrieves ALL records. Custom paging should use database stored procdure to fetch only the records of the current page.
    How can that 'custom' paging be implemented (WITHOUT using objectdatasource) ?

    The code in this post is aimed at those who need help enabling sorting/paging without a DataSourceControl, not advanced techniques. If you're not satisfied with that, I invite you to modify the code as you are expecting it to function.

     

    How would someone add something like "Showing results 1-15 of 30 results" to the top of the gv?

     

    - Shaun
  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    12-15-2006, 9:32 AM
    Locked
    • Member
      310 point Member
    • sduffy
    • Member since 05-25-2005, 2:50 PM
    • Posts 68

    sduffy:
    How would someone add something like "Showing results 1-15 of 30 results" to the top of the gv?

    I did it programatically. Not sure if this is best practice or not but here's my solution:

     

    <asp:Label ID="lblResults" runat="server"></asp:Label>
       
    private void SetPagingDisplay(int size)
        {
    
            int gvPsize = gvSearchResults.PageSize;
            int curPage = gvSearchResults.PageIndex + 1;
            int resFrom = 0;
            int resTo = 0;
            if (gvPsize > 1 && curPage > 1)
            {
                resFrom = ((curPage - 1) * gvPsize) + 1;
                resTo = curPage * gvPsize;
            }
            else
            {
                resFrom = 1;
                resTo = gvPsize;
            }
            lblResults.Text = String.Format("Showing Results {0}-{1} of {2} results", resFrom.ToString(), resTo.ToString(), size.ToString());
        }

     I then just called this from inside my databind function and the sorting and paging functions.
     

    - Shaun
  • Re: HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

    12-29-2006, 3:40 PM
    Locked
    • Member
      4 point Member
    • lunico
    • Member since 12-29-2006, 8:35 PM
    • Posts 2

    I am having the same problem sorting.  I have an XML file where I read all the data into a gridview and it works great, but I want the gridview to be sorted desc. 

    I am getting the following error: The GridView 'GridView1' fired event Sorting which wasn't handled.

    I have sorting set to on. The user does not need to be able to sort it.  I just want it to load sorted in desc order.

     

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    FileLocation = Server.MapPath(

    "NewsLettersList.xml")

    If Page.IsPostBack = False Then

    Dim oDs As New DataSet

    oDs.ReadXml(FileLocation)

    'Read XML File

    Dim i As Integer = oDs.Tables.Count

    GridView1.DataSource = oDs

    Dim sortExpression As String = GridView1.Columns.Item(2).SortExpression 

    GridView1.Sort(sortExpression, SortDirection.Descending)

    GridView1.DataBind()

    End If

    End Sub
Page 9 of 13 (186 items) « First ... < Previous 7 8 9 10 11 Next > ... Last »