Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How custom paging works with oracle database 1

Status
Not open for further replies.

taree

Technical User
May 31, 2008
316
US
I am working to create a customize paging using oracle database.My code is only gives me the first 20 records from the database and I know because everytime it loads it get the value 20 and it does not show the paging number. I would like to have the paging to be displayed in the first page and the gridview to show the next 20 items every time I change the page nubmer. How can I do this.

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


 Sub BindData()

        Dim pageSize As Integer = 20
        Dim UpperRowNumber As Integer = ((gvItem.PageIndex + 1) * pageSize) + 1
        Dim LowerRowNumber As Integer = (((gvItem.PageIndex + 1) - 1) * pageSize) + 1

        Label1.Text = gvItem.PageIndex + 1
        Label2.Text = gvItem.PageCount


        Dim connectionString As String = ConnectionStrings("ConnectionString").ConnectionString
        Dim oOracleConn As OracleConnection = New OracleConnection(connectionString)
        oOracleConn.Open()

        Dim strStringBuilder As StringBuilder
        strStringBuilder = New StringBuilder
        With strStringBuilder

            .Append("SELECT b.*, ROWNUM ")
            .Append("FROM (SELECT a.*, func_get_unit_name (unit_name) plan_unit_description, ROWNUM r__ ")
            .Append("FROM (SELECT   (SUBSTR (item, 1, 4) || '.' || SUBSTR (item, 5) ) item_number, ")
            .Append(" idescr short_description, idescrl long_description, ")
            .Append(" iunits unit_name, ispecyr spec_year, iobselet, item ")
            .Append("FROM(itemlist) ")
            .Append("WHERE item <> '2999509/00001' ")
            .Append(" AND iobselet = 'N' ")
            .Append(" AND ispecyr = '05' ")
            .Append(" ORDER BY item) a ")
            .Append(" WHERE ROWNUM < (:rownumberA)) b ")
            .Append(" WHERE r__ >= :rownumberB ")

        End With

        'CREATE A NEW COMMAND AND PASS THE SQL STATEMENT / CONNECTION OBJECT
        Dim cmdItemDetail As OracleCommand = New OracleCommand()
        cmdItemDetail.Parameters.Add(":rownumberA", OracleType.Int32).Value = UpperRowNumber
        cmdItemDetail.Parameters.Add(":rownumberB", OracleType.Int32).Value = LowerRowNumber

        cmdItemDetail.Connection = oOracleConn
        cmdItemDetail.CommandType = CommandType.Text
        cmdItemDetail.CommandText = strStringBuilder.ToString
        ' Dim adItemDetail As New OleDbDataAdapter(cmdItemDetail)
        Dim adItemDetail As New OracleDataAdapter(cmdItemDetail)
        Dim dsItemDetail As New DataSet

        'Fill the dataset with the result of our query from the specified command
        adItemDetail.Fill(dsItemDetail, "ItemDetails")
        'Bind the DataSet to the GridView
        gvItem.DataSource = dsItemDetail
        gvItem.DataBind()



    End Sub
 
Every time your page loads, it calls bind data and will load the first set of items
 
thank you jbenson001 for reply. so, how can I get the page number from the gridview and pass to the query.
if it helps here is my html page. thank you for the help.
Code:
<%@ Page Language="VB"  MaintainScrollPositionOnPostback="true" AutoEventWireup="false" EnableViewState="false" CodeFile="custPaging.aspx.vb" Inherits="ItemPerLine" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] >
<head>
<title> projects</title>
</head>
<body>


    <form id="form1" runat="server">


        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
            Height="18px" Width="101px">
            <asp:ListItem>10</asp:ListItem>
            <asp:ListItem>20</asp:ListItem>
            <asp:ListItem>30</asp:ListItem>
        </asp:DropDownList>

        <asp:Label ID="lblView" runat="server" ></asp:Label>

            <asp:GridView ID="gvItem" 
               runat="server" 
               CellPadding="4" 
               ForeColor="#333333"
               Width="99%"
               HorizontalAlign="Left"
               AutoGenerateColumns="False" 
               AllowPaging="True" 
               PageSize="20"
               OnPageIndexChanging ="gvItem_PageIndexChanging"
               AllowSorting="True"  
               BackColor="PapayaWhip" Font-Size="Small" 
               Font-Bold="False" style=""  >


                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerSettings Position="TopAndBottom" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" Font-Size="Small" HorizontalAlign="Left" />
                 <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Font-Size="Small" HorizontalAlign="Left" />
                <PagerStyle BackColor="#FFE0C0" ForeColor="Black" HorizontalAlign="Right"  Font-Size="X-Large" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" Font-Size="Smaller" HorizontalAlign="Left" />
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />                                         
                <Columns>

                    <asp:BoundField DataField="Item_Number" HeaderText="Line Number" >
                        <HeaderStyle Font-Size="Small" />
                        <ItemStyle Font-Size="Smaller" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Short_Description" HeaderText="Item Number" >
                        <HeaderStyle Font-Size="Small" />
                        <ItemStyle Font-Size="Smaller" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Long_Description" HeaderText="Item Description" >
                        <HeaderStyle Font-Size="Small" />
                        <ItemStyle Font-Size="Smaller" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Unit_Name" HeaderText="Unit_Name" >
                        <HeaderStyle Font-Size="Small" />
                        <ItemStyle Font-Size="Smaller" />
                    </asp:BoundField>

                </Columns>

            </asp:GridView>


 </form>
</body>
</html>
 
Thank you jbenson001 for the links.with the help of the links I am able to manage to see the output. the only problem is when the page load event the gridview is empty and I have to make a selection for the number of rows per page inorder for the gridview to be populated. Do I miss something here? thank you for the help
Code:
Imports System
Imports System.Data
Imports System.IO
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
'Imports Oracle.DataAccess.Client
Imports System.Configuration.ConfigurationManager
Imports System.Data.OracleClient

Namespace CustomGridView
    Partial Public Class CustomGridView
        Inherits System.Web.UI.Page
        Protected Shared currentPageNumber As Integer
        Protected Shared PAGE_SIZE As Integer

#Region "Page Events"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If Not Page.IsPostBack Then
                lblMessage.Text = ""
                currentPageNumber = 1
                PAGE_SIZE = 10
                ViewState("SortOrder") = "ASC"
                pBindData(Nothing, False)
            End If
        End Sub

        Protected Sub GetPageIndex(ByVal sender As Object, ByVal e As CommandEventArgs)

            Select Case e.CommandName
                Case "First"
                    currentPageNumber = 1
                    Exit Select

                Case "Previous"
                    currentPageNumber = CType(Int32.Parse(ddlPage.SelectedValue) - 1, Integer)
                    Exit Select

                Case "Next"
                    currentPageNumber = CType((ddlPage.SelectedValue) + 1, Integer)
                    Exit Select

                Case "Last"
                    currentPageNumber = CType((lblTotalPages.Text), Integer)
                    Exit Select
            End Select

            pBindData(Nothing, False)
        End Sub

        Protected Sub ddlRows_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            currentPageNumber = 1
            grdViewCustPaging.PageSize = Int32.Parse(ddlRows.SelectedValue)
            PAGE_SIZE = Int32.Parse(ddlRows.SelectedValue)
            pBindData(Nothing, False)
        End Sub

        Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlPage.SelectedIndexChanged
            currentPageNumber = CType(ddlPage.SelectedValue, Integer)
            pBindData(Nothing, False)
        End Sub

        Protected Sub grdViewCustPaging_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.DataRow Then
                For i As Integer = 0 To e.Row.Cells.Count - 1
                    e.Row.Cells(i).CssClass = "GridItem1"
                    If e.Row.Cells(i).Text.Trim() <> "&nbsp;" Then
                        e.Row.Cells(i).Attributes.Add("title", e.Row.Cells(i).Text)
                    End If
                Next
                e.Row.Attributes.Add("onmouseover", "javascript:this.className = 'GridRowHover'")
                e.Row.Attributes.Add("onmouseout", "javascript:this.className = ''")
                e.Row.TabIndex = -1
                e.Row.Attributes("onclick") = String.Format("javascript:SelectRow(this, {0});", e.Row.RowIndex)
                e.Row.Attributes("onkeydown") = "javascript:return SelectSibling(event);"
                e.Row.Attributes("onselectstart") = "javascript:return false;"
            End If
        End Sub

        Protected Sub grdViewCustPaging_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
            If String.Compare(Convert.ToString(ViewState("SortOrder")), " ASC", True) = 0 Then
                ViewState("SortOrder") = " DESC"
            Else
                ViewState("SortOrder") = " ASC"
            End If
            pBindData(e.SortExpression + ViewState("SortOrder"), False)
        End Sub

        Protected Sub lnkbtnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
            If grdViewCustPaging.Rows.Count > 0 Then
                pBindData(Nothing, True)
                'export to excel
                pExportGridToExcel(grdViewCustPaging, "CustomGridView_" + Convert.ToString(ViewState("ReportTime")) + ".xls")
            End If
        End Sub

#End Region

#Region "Public Method"

        Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        End Sub

#End Region

#Region "Private Method"

        Private Function GetTotalPages(ByVal totalRows As Double) As Integer
            Dim totalPages As Integer = CInt(Math.Ceiling(totalRows / PAGE_SIZE))

            Return totalPages
        End Function

        Private Sub pBindData(ByVal aSortExp As String, ByVal aIsCompleteData As Boolean)

            Dim connectionString As String = ConnectionStrings("ConnectionString1").ConnectionString
            Dim oOracleConn As OracleConnection = New OracleConnection(connectionString)
            oOracleConn.Open()
            Dim ds As DataSet = Nothing
            Dim objAdp As OracleDataAdapter = Nothing
            Dim cmdItemDetail As OracleCommand = New OracleCommand()


            Try

                With cmdItemDetail
                    .Connection = oOracleConn
                    .CommandText = "gettrnsportitems1a"
                    .CommandType = CommandType.StoredProcedure
                    .Parameters.Add(New OracleParameter("inStartRowIndex", OracleType.Number)).Direction = ParameterDirection.Input
                    .Parameters("inStartRowIndex").Value = ((currentPageNumber - 1) * PAGE_SIZE) + 1
                    .Parameters.Add(New OracleParameter("inEndRowIndex", OracleType.Number)).Direction = ParameterDirection.Input

                    If aIsCompleteData Then
                        cmdItemDetail.Parameters("inEndRowIndex").Value = -1
                    Else
                        cmdItemDetail.Parameters("inEndRowIndex").Value = (currentPageNumber * PAGE_SIZE)
                    End If
             
                    .Parameters.Add(New OracleParameter("inSortExp", OracleType.Char)).Direction = ParameterDirection.Input
                    If aSortExp = Nothing Then
                        .Parameters("inSortExp").Value = "item"
                    Else
                        .Parameters("inSortExp").Value = aSortExp
                    End If

                    .Parameters.Add(New OracleParameter("outTotalRows", OracleType.Number)).Direction = ParameterDirection.Output
                    .Parameters.Add(New OracleParameter("outitemcur", OracleType.Cursor)).Direction = ParameterDirection.Output

                End With


                ds = New DataSet()

                ''Instatiate Data Adopter
                objAdp = New OracleDataAdapter(cmdItemDetail)

                ''Fill Data Set
                objAdp.Fill(ds)

                ''Bind Data to Grids
                grdViewCustPaging.DataSource = ds.Tables("Table")
                grdViewCustPaging.DataBind()

                ViewState("ReportTime") = DateTime.Now

                ''get the total rows 
                Dim totalRows As Double = CInt(cmdItemDetail.Parameters("outTotalRows").Value)

                lblTotalPages.Text = GetTotalPages(totalRows).ToString()

                ddlPage.Items.Clear()
                For i As Integer = 1 To Convert.ToInt32(lblTotalPages.Text)
                    ddlPage.Items.Add(New ListItem(i.ToString()))
                Next

                ddlPage.SelectedValue = currentPageNumber.ToString()

                If currentPageNumber = 1 Then
                    lnkbtnPre.Enabled = False
                    lnkbtnPre.CssClass = "GridPagePreviousInactive"
                    lnkbtnFirst.Enabled = False
                    lnkbtnFirst.CssClass = "GridPageFirstInactive"

                    If Int32.Parse(lblTotalPages.Text) > 0 Then
                        lnkbtnNext.Enabled = True
                        lnkbtnNext.CssClass = "GridPageNextActive"
                        lnkbtnLast.Enabled = True
                        lnkbtnLast.CssClass = "GridPageLastActive"
                    Else
                        lnkbtnNext.Enabled = False
                        lnkbtnNext.CssClass = "GridPageNextInactive"
                        lnkbtnLast.Enabled = False
                        lnkbtnLast.CssClass = "GridPageLastInactive"
                    End If
                Else

                    lnkbtnPre.Enabled = True
                    lnkbtnPre.CssClass = "GridPagePreviousActive"
                    lnkbtnFirst.Enabled = True
                    lnkbtnFirst.CssClass = "GridPageFirstActive"

                    If currentPageNumber = Int32.Parse(lblTotalPages.Text) Then
                        lnkbtnNext.Enabled = False
                        lnkbtnNext.CssClass = "GridPageNextInactive"
                        lnkbtnLast.Enabled = False
                        lnkbtnLast.CssClass = "GridPageLastInactive"
                    Else
                        lnkbtnNext.Enabled = True
                        lnkbtnNext.CssClass = "GridPageNextActive"
                        lnkbtnLast.Enabled = True
                        lnkbtnLast.CssClass = "GridPageLastActive"
                    End If

                End If
            Catch ex As Exception
                lblMessage.Text = ex.Message
            Finally
                If cmdItemDetail IsNot Nothing Then
                    cmdItemDetail.Dispose()
                End If
                If objAdp IsNot Nothing Then
                    objAdp.Dispose()
                End If
                If ds IsNot Nothing Then
                    ds.Dispose()
                End If
                If (oOracleConn IsNot Nothing) AndAlso (oOracleConn.State = ConnectionState.Open) Then
                    oOracleConn.Close()
                    oOracleConn.Dispose()
                End If
                cmdItemDetail = Nothing
                objAdp = Nothing
                ds = Nothing
                oOracleConn = Nothing
            End Try
        End Sub

        Private Sub pExportGridToExcel(ByVal grdGridView As GridView, ByVal fileName As [String])
            Response.Clear()
            Response.AddHeader("content-disposition", [String].Format("attachment;filename={0}", fileName))
            Response.Charset = ""
            Response.ContentType = "application/vnd.xls"

            Dim stringWrite As New StringWriter()
            Dim htmlWrite As New HtmlTextWriter(stringWrite)
            ClearControls(grdViewCustPaging)
            grdGridView.RenderControl(htmlWrite)
            Response.Write(stringWrite.ToString().Replace(HttpUtility.HtmlDecode("&nbsp;"), " "))
            Response.[End]()
        End Sub

        Private Sub ClearControls(ByVal control As Control)
            For i As Integer = control.Controls.Count - 1 To 0 Step -1
                ClearControls(control.Controls(i))
            Next
            If Not (TypeOf control Is TableCell) Then
                If control.[GetType]().GetProperty("SelectedItem") IsNot Nothing Then
                    Dim literal As New LiteralControl()
                    control.Parent.Controls.Add(literal)
                    Try
                        literal.Text = DirectCast(control.[GetType]().GetProperty("SelectedItem").GetValue(control, Nothing), [String])
                    Catch
                    End Try
                    control.Parent.Controls.Remove(control)
                ElseIf control.[GetType]().GetProperty("Text") IsNot Nothing Then
                    Dim literal As New LiteralControl()
                    control.Parent.Controls.Add(literal)
                    literal.Text = DirectCast(control.[GetType]().GetProperty("Text").GetValue(control, Nothing), [String])
                    control.Parent.Controls.Remove(control)
                End If
            End If
            Return
        End Sub

#End Region
    End Class
End Namespace
 
I think I got the problem why I get the blank gridview when the page loads. here the fix. Sorting is not working for now and once I get that to work I will post the entire code for someone who is interested.In the mean time if you have any idea why sorting is not working please let me know. your help is very much appreicated.
Code:
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.IsPostBack Then
                lblMessage.Text = ""
                currentPageNumber = 1
                PAGE_SIZE = 10
                ViewState("SortOrder") = "ASC"
                pBindData(" ", False)
            End If
        End Sub
 
I would start by tracing through your code and make sure you are passing the correct sorting values to your proc.
 
Thank you Jbenson001 for your reply. that is what I am doing. I am getting this eorr now.
"Arithmetic operation resulted in an overflow."
 
You will have to see on what line that error happens and see what the issue is.
 
the eror is on line 111. I am not sure why? it is casting to an integer....

Code:
Exception Details: System.OverflowException: Arithmetic 

operation resulted in an overflow.

Source Error: 


Line 109:
Line 110:        Private Function GetTotalPages(ByVal totalRows As Double) As Integer
Line 111:            Dim totalPages As Integer = CInt(Math.Ceiling(totalRows / PAGE_SIZE))
Line 112:
Line 113:            Return totalPages

 
Mark, totalrows = 8579 and pagesize = 10. the weird part is when I run it from my local machine I do not get this error message.
 
Mark, I found a work around for this. the problem was everytime I clik the next button the value for pagesize loses its value. this happent every other click. I just add to the page load event the below line and seems to work ok. I am not sure if that is the best practice but it is working for me. I need to do more test though...Guys I thank you for your help
Code:
 If Not Page.IsPostBack Then
                lblMessage.Text = ""
                currentPageNumber = 1
                PAGE_SIZE = 10
                ViewState("SortOrder") = "ASC"
                pBindData(" ", False)
            Else
   --this is the line I added-------------
             PAGE_SIZE = ddlRows.SelectedValue
            End If
 
just a follow up question.

i am fetching the data from the oracle db to the gridview.
i am sorting the gridview columns(item)using "order by item"
in the query. I mean, i am not sorting using the datview.sort property.
sorting and paging all working fine...

my problem is:

when i go to nextpage(page2) and clicked on header to sort,
it is sorting all the data. i need to sort only the data in page2.
i know the reason is the sorting is from database not in the grid.

how can I achieve this in my case....please help

thanks
 
Not sure I understand your question. You want to page but only sort when the user is on page 2?. Are you allowing them to click the headers to sort?
 
what i am trying to say is for example if the user click page2. I want to sort the rows in page2 in descending and ascending order. Yes, I am using headers to sort.hope this makes sense. right now when it does sorting it checks the entire rows.
 
Not sure what you mean by it checks all the rows. If your stored procedure is written correctly it will only return the set of rows you need in the correct order.
 
Finally, I got it to work. thank you all for the help and I am posting the entire code just in case someone happen to be interested to learn.

Code:
CREATE OR REPLACE PROCEDURE gettrnsportitems2a (
   instartrowindex   IN       NUMBER,
   inendrowindex     IN       NUMBER,
   insortexp         IN       VARCHAR2,
   outtotalrows      OUT      NUMBER,
   outitemcur        OUT      sys_refcursor
)
IS
   sortexp   VARCHAR2 (20) := LOWER (TRIM (insortexp));
BEGIN
   SELECT   COUNT (*)
       INTO outtotalrows
       FROM itemlist
      WHERE item <> '2999509/00001' AND iobselet = 'N' AND ispecyr = '05'
   ORDER BY item;

   IF (inendrowindex = -1)
   THEN
      OPEN outitemcur FOR
         SELECT   (SUBSTR (item, 1, 4) || '.' || SUBSTR (item, 5)
                  ) itemnumber, idescr, idescrl, iunits, ispecyr, iobselet,
                  item
             FROM itemlist
            WHERE item <> '2999509/00001' AND iobselet = 'N'
                  AND ispecyr = '05'
         ORDER BY item;
   ELSE
      BEGIN
         OPEN outitemcur FOR
            SELECT   itemnumber, r, idescr, idescrl, iunits, ispecyr,
                     iobselet
                FROM (SELECT (SUBSTR (item, 1, 4) || '.' || SUBSTR (item, 5)
                             ) itemnumber,
                             idescr, idescrl, iunits, ispecyr, iobselet,
                             ROW_NUMBER () OVER (ORDER BY item) r
                        FROM itemlist
                       WHERE item <> '2999509/00001'
                         AND iobselet = 'N'
                         AND ispecyr = '05')
               WHERE r BETWEEN instartrowindex AND inendrowindex
            ORDER BY DECODE (sortexp, 'itemnumber asc', itemnumber) ASC,
                     DECODE (sortexp, 'itemnumber desc', itemnumber) DESC,
                     DECODE (sortexp, 'idescr asc', idescr) ASC,
                     DECODE (sortexp, 'idescr desc', idescr) DESC,
                     DECODE (sortexp, 'idescrl asc', idescrl) ASC,
                     DECODE (sortexp, 'idescrl desc', idescrl) DESC,
                     DECODE (sortexp, 'iunits asc', iunits) ASC,
                     DECODE (sortexp, 'iunits desc', iunits) DESC,
                     DECODE (sortexp, 'ispecyr asc', ispecyr) ASC,
                     DECODE (sortexp, 'ispecyr desc', ispecyr) DESC;
      END;
   END IF;
END;
/

Code:
Imports System
Imports System.Data
Imports System.IO
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Configuration.ConfigurationManager
Imports System.Data.OracleClient

Namespace CustomGridView
    Partial Public Class CustomGridView
        Inherits System.Web.UI.Page
        Protected Shared currentPageNumber As Integer
        Protected Shared PAGE_SIZE As Integer
        Dim ds As DataSet = Nothing


#Region "Page Events"
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.IsPostBack Then
                lblMessage.Text = ""
                currentPageNumber = 1
                PAGE_SIZE = 10
                ViewState("SortOrder") = "ASC"
                pBindData(Nothing, False)
            Else
                PAGE_SIZE = ddlRows.SelectedValue
            End If


        End Sub

        Protected Sub GetPageIndex(ByVal sender As Object, ByVal e As CommandEventArgs)

            Select Case e.CommandName
                Case "First"
                    currentPageNumber = 1
                    Exit Select

                Case "Previous"
                    currentPageNumber = Int32.Parse(ddlPage.SelectedValue) - 1
                    Exit Select

                Case "Next"
                    currentPageNumber = Int32.Parse(ddlPage.SelectedValue) + 1
                    Exit Select

                Case "Last"
                    currentPageNumber = Int32.Parse(lblTotalPages.Text)
                    Exit Select
            End Select

            pBindData(Nothing, False)
        End Sub

        Protected Sub ddlRows_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            currentPageNumber = 1
            grdViewCustPaging.PageSize = Int32.Parse(ddlRows.SelectedValue)
            PAGE_SIZE = Int32.Parse(ddlRows.SelectedValue)
            pBindData(Nothing, False)
        End Sub

        Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            currentPageNumber = Int32.Parse(ddlPage.SelectedValue)
            pBindData(" ", False)
        End Sub

        Protected Sub grdViewCustPaging_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.DataRow Then
                For i As Integer = 0 To e.Row.Cells.Count - 1
                    e.Row.Cells(i).CssClass = "GridItem1"
                    If e.Row.Cells(i).Text.Trim() <> "&nbsp;" Then
                        e.Row.Cells(i).Attributes.Add("title", e.Row.Cells(i).Text)
                    End If
                Next
                e.Row.Attributes.Add("onmouseover", "javascript:this.className = 'GridRowHover'")
                e.Row.Attributes.Add("onmouseout", "javascript:this.className = ''")
                e.Row.TabIndex = -1
                e.Row.Attributes("onclick") = String.Format("javascript:SelectRow(this, {0});", e.Row.RowIndex)
                e.Row.Attributes("onkeydown") = "javascript:return SelectSibling(event);"
                e.Row.Attributes("onselectstart") = "javascript:return false;"
            End If
        End Sub
        Protected Sub grdViewCustPaging_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)

            If String.Compare(Convert.ToString(ViewState("SortOrder")), " " & "ASC", True) = 0 Then
                ViewState("SortOrder") = " " & "DESC"
            Else
                ViewState("SortOrder") = " " & "ASC"
            End If
            pBindData(e.SortExpression + ViewState("SortOrder"), False)
        End Sub
        Protected Sub lnkbtnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
            If grdViewCustPaging.Rows.Count > 0 Then
                pBindData(" ", True)
                'export to excel
                pExportGridToExcel(grdViewCustPaging, "CustomGridView_" + Convert.ToString(ViewState("ReportTime")) + ".xls")
            End If
        End Sub

#End Region

#Region "Public Method"

        Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        End Sub

#End Region

#Region "Private Method"

        Private Function GetTotalPages(ByVal totalRows As Integer) As Integer
            lblTotal.Text = totalRows.ToString
            lblSize.Text = PAGE_SIZE.ToString

            Dim totalPages As Integer = CInt(Math.Ceiling(totalRows / PAGE_SIZE))
            Return totalPages
        End Function

        Private Sub pBindData(ByVal aSortExp As String, ByVal aIsCompleteData As Boolean)
            Dim test As String = aSortExp

            Dim connectionString As String = ConnectionStrings("ConnectionString1").ConnectionString
            Dim oOracleConn As OracleConnection = New OracleConnection(connectionString)
            oOracleConn.Open()
            Dim ds As DataSet = Nothing
            Dim objAdp As OracleDataAdapter = Nothing
            Dim cmdItemDetail As OracleCommand = New OracleCommand()


            Try

                With cmdItemDetail
                    .Connection = oOracleConn
                    '  .CommandText = "trnsportitems.gettrnsportitems"
                    .CommandText = "gettrnsportitems2a"
                    .CommandType = CommandType.StoredProcedure
                    .Parameters.Add(New OracleParameter("inStartRowIndex", OracleType.Number)).Direction = ParameterDirection.Input
                    .Parameters("inStartRowIndex").Value = ((currentPageNumber - 1) * PAGE_SIZE) + 1
                    .Parameters.Add(New OracleParameter("inEndRowIndex", OracleType.Number)).Direction = ParameterDirection.Input

                    If aIsCompleteData Then
                        cmdItemDetail.Parameters("inEndRowIndex").Value = -1
                    Else
                        cmdItemDetail.Parameters("inEndRowIndex").Value = (currentPageNumber * PAGE_SIZE)
                    End If

                    .Parameters.Add(New OracleParameter("inSortExp", OracleType.Char)).Direction = ParameterDirection.Input

                    If aSortExp = Nothing Then
                        .Parameters("inSortExp").Value = " "
                    Else
                        .Parameters("inSortExp").Value = aSortExp
                    End If

                    .Parameters.Add(New OracleParameter("outTotalRows", OracleType.Number)).Direction = ParameterDirection.Output
                    .Parameters.Add(New OracleParameter("outitemcur", OracleType.Cursor)).Direction = ParameterDirection.Output

                End With


                ds = New DataSet()

                ''Instatiate Data Adopter
                objAdp = New OracleDataAdapter(cmdItemDetail)

                ''Fill Data Set
                objAdp.Fill(ds)

                ''Bind Data to Grids
                grdViewCustPaging.DataSource = ds.Tables("Table")
                grdViewCustPaging.DataBind()

                ViewState("ReportTime") = DateTime.Now

                ''get the total rows 
                Dim totalRows As Double = CInt(cmdItemDetail.Parameters("outTotalRows").Value)

                lblTotalPages.Text = GetTotalPages(totalRows).ToString()

                ddlPage.Items.Clear()
                For i As Integer = 1 To Convert.ToInt32(lblTotalPages.Text)
                    ddlPage.Items.Add(New ListItem(i.ToString()))
                Next

                ddlPage.SelectedValue = currentPageNumber.ToString()

                If currentPageNumber = 1 Then
                    lnkbtnPre.Enabled = False
                    lnkbtnPre.CssClass = "GridPagePreviousInactive"
                    lnkbtnFirst.Enabled = False
                    lnkbtnFirst.CssClass = "GridPageFirstInactive"

                    If Int32.Parse(lblTotalPages.Text) > 0 Then
                        lnkbtnNext.Enabled = True
                        lnkbtnNext.CssClass = "GridPageNextActive"
                        lnkbtnLast.Enabled = True
                        lnkbtnLast.CssClass = "GridPageLastActive"
                    Else
                        lnkbtnNext.Enabled = False
                        lnkbtnNext.CssClass = "GridPageNextInactive"
                        lnkbtnLast.Enabled = False
                        lnkbtnLast.CssClass = "GridPageLastInactive"
                    End If
                Else

                    lnkbtnPre.Enabled = True
                    lnkbtnPre.CssClass = "GridPagePreviousActive"
                    lnkbtnFirst.Enabled = True
                    lnkbtnFirst.CssClass = "GridPageFirstActive"

                    If currentPageNumber = Int32.Parse(lblTotalPages.Text) Then
                        lnkbtnNext.Enabled = False
                        lnkbtnNext.CssClass = "GridPageNextInactive"
                        lnkbtnLast.Enabled = False
                        lnkbtnLast.CssClass = "GridPageLastInactive"
                    Else
                        lnkbtnNext.Enabled = True
                        lnkbtnNext.CssClass = "GridPageNextActive"
                        lnkbtnLast.Enabled = True
                        lnkbtnLast.CssClass = "GridPageLastActive"
                    End If

                End If
            Catch ex As Exception
                lblMessage.Text = ex.Message
            Finally
                If cmdItemDetail IsNot Nothing Then
                    cmdItemDetail.Dispose()
                End If
                If objAdp IsNot Nothing Then
                    objAdp.Dispose()
                End If
                If ds IsNot Nothing Then
                    ds.Dispose()
                End If
                If (oOracleConn IsNot Nothing) AndAlso (oOracleConn.State = ConnectionState.Open) Then
                    oOracleConn.Close()
                    oOracleConn.Dispose()
                End If
                cmdItemDetail = Nothing
                objAdp = Nothing
                ds = Nothing
                oOracleConn = Nothing
            End Try
        End Sub

        Private Sub pExportGridToExcel(ByVal grdGridView As GridView, ByVal fileName As [String])
            Response.Clear()
            Response.AddHeader("content-disposition", [String].Format("attachment;filename={0}", fileName))
            Response.Charset = ""
            Response.ContentType = "application/vnd.xls"

            Dim stringWrite As New StringWriter()
            Dim htmlWrite As New HtmlTextWriter(stringWrite)
            ClearControls(grdViewCustPaging)
            grdGridView.RenderControl(htmlWrite)
            Response.Write(stringWrite.ToString().Replace(HttpUtility.HtmlDecode("&nbsp;"), " "))
            Response.[End]()
        End Sub

        Private Sub ClearControls(ByVal control As Control)
            For i As Integer = control.Controls.Count - 1 To 0 Step -1
                ClearControls(control.Controls(i))
            Next
            If Not (TypeOf control Is TableCell) Then
                If control.[GetType]().GetProperty("SelectedItem") IsNot Nothing Then
                    Dim literal As New LiteralControl()
                    control.Parent.Controls.Add(literal)
                    Try
                        literal.Text = DirectCast(control.[GetType]().GetProperty("SelectedItem").GetValue(control, Nothing), [String])
                    Catch
                    End Try
                    control.Parent.Controls.Remove(control)
                ElseIf control.[GetType]().GetProperty("Text") IsNot Nothing Then
                    Dim literal As New LiteralControl()
                    control.Parent.Controls.Add(literal)
                    literal.Text = DirectCast(control.[GetType]().GetProperty("Text").GetValue(control, Nothing), [String])
                    control.Parent.Controls.Remove(control)
                End If
            End If
            Return
        End Sub

#End Region

       
    End Class
End Namespace
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top