Solved

Change page using GridView

Posted on 2008-10-15
22
1,058 Views
Last Modified: 2012-05-05
I have a gridview that needs to show 10 records at a time. (I know how to do this).  I want it to search through each page to find some text.  Once it finds that text I want the gridview to show the correct page.   I found some code to help me go through all of the rows (do not remember where).  This allows me to find the column that I want and what the text is for each cell.  I then put a for loop to go through all pages.  

This code is called on the PAGE LOAD event.

My problem is that it always ends on the last page and everytime it reads cellresult.text it is reading the results from the first page.  So even though my gridview1.pageindex = lngx (say 56) it is still reading the results from page 1.  Once all loops have completed the page that shows is the last page.

I was hoping that gridview1.pageindex = lngx  would move the page but it does not seem to work.
'this first part gives me the correct page count w/o this pagecount = 0

Dim StrIC As String

StrIC = "M-Test"

Dim lngrow As Int32 ' was thinking of using this before but don't use it now.

Dim lngX As Long

If GridView1.PageCount = 0 Then

   For Each row As GridViewRow In GridView1.Rows()

   Next

End If
 

For lngX = 0 To GridView1.PageCount

            GridView1.PageIndex = lngX

            For Each row As GridViewRow In GridView1.Rows()

                lngrow = lngrow + 1

                For Each cellResult As DataControlFieldCell In row.Cells

                    Dim cellDCF As DataControlField = cellResult.ContainingField

                    Dim cellID As String = cellDCF.HeaderText
 

                    If cellID.ToString = "IC" Then
 

                        Dim cellValue As String = CStr(cellResult.Text)
 

                        If UCase(cellValue) = UCase(StrIC) Then
 

                            cellResult.Visible = True

                            cellResult.BackColor = Drawing.Color.Aqua

                            Exit Sub

                        Else

                            cellResult.BackColor = Drawing.Color.Black
 

                        End If

                    End If

                Next

            Next

        Next

Open in new window

0
Comment
Question by:Deadcats
  • 11
  • 11
22 Comments
 
LVL 22

Expert Comment

by:prairiedog
ID: 22724112
Try this:
For lngX = 0 To GridView1.PageCount - 1

0
 

Author Comment

by:Deadcats
ID: 22724295
Hi Prairiedog,

I tried your suggestion but the same thing happens.  It goes through the loop like it is going through each page but the text cellresult.text always returns the values from page 1.  Once the main loop has finished it opens the page and the last page of the gridview is displayed.  

Thanks for the suggestion.
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22724371
Move this line: GridView1.PageIndex = lngX, right before "Exit Sub". You only need to change the page index until you find the needed row.
0
 

Author Comment

by:Deadcats
ID: 22725002
Thanks again for the suggestion.
Unfortunately this has not solved my problem.  It is still only reading the first page of the gridview instead of every page. Page 1-492    

So for every time I do
For lngX = 0 To GridView1.PageCount - 1
next
it moves to the next page (or so it says)  but the text it reads is always from page one.
0
 
LVL 22

Accepted Solution

by:
prairiedog earned 500 total points
ID: 22725090
OK, scratch my last suggestion. Let's try this. Every time you change PageIndex, GridView will not change the page automatically, you will have to call GridView.DataBind to force it to change to the new page. So try adding GridView1.DataBind() after GridView1.PageIndex = lngX
0
 

Author Comment

by:Deadcats
ID: 22725229
That works.  It is slow, very slow but it works.    

Any thoughts on how to speed this up?
0
 
LVL 22

Assisted Solution

by:prairiedog
prairiedog earned 500 total points
ID: 22725307
It is going to be slow, because you are binding the GridView many times. I would try a different approach. I am attaching a sample code that I used before to highlight a row in a GridView based on the record ID, it should get you started. If you have questions about the sample, let me know.
Private Sub HighlightRow(ByVal keyID As Integer)

	Dim id As Integer = 0

	Dim pSize As Integer = Me.GridView2.PageSize

	Dim dr As DataRow

	Dim ds As DataSet = CType(Session("DataSet"), DataSet)

	For i As Integer = 0 To ds.Tables(0).Rows.Count - 1

		dr = ds.Tables(0).Rows(i)

		id = dr("EmployeeID")

		If (id = keyID) Then

			Me.GridView2.PageIndex = i / pSize

			Me.GridView2.DataSource = ds

			Me.GridView2.DataBind()
 

			For Each gvr As GridViewRow In Me.GridView2.Rows

				If (Me.GridView2.DataKeys(gvr.RowIndex).Value = keyID) Then

					gvr.BackColor = Drawing.Color.Yellow

				End If

			Next

			Exit Sub

		End If

	Next

End Sub

Open in new window

0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22725337
Basically what it does is to loop through the datatable (not the GridView) to find the record that meets your search criteria. Once found it, based on the row index and GridView's PageSize, to calculate the page index of the found row, then rebind the GridView.
0
 

Author Comment

by:Deadcats
ID: 22725410
I think I will be able to work with this.  

The database I am connecting to is not part of the website at all. I do not have any connection strings in my web.config.  Also the database can be located anywhere on my network and I have to be able to access it.  I have done this many of times through VB and have done it with VB.NET but after creating the connection to read write or delete the data I have never done anything like

Dim dr As DataRow
Dim ds As DataSet = CType(Session("DataSet"), DataSet)
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22725516
I used DataSet as the DataSource for my GridView in my example, and I stored it in Sesssion so I didn't have to query database again to get the data. But for large datatable (or dataset), it is not a good idea to store it in Seesion, because it consumes a lot of memory.
How do you get your GridView bound at the first place?
0
 

Author Comment

by:Deadcats
ID: 22725628
I attached the code below.
I am not sure if this is the best way to do it. But I am working with an Access Database ( I do not have any other choice).  
StrQry = "SELECT ITM.Counter, ITM.COST, ITM.IC, ITM.NAME, ITM.PRICE, ITM.ITOT FROM ITM "

            StrQry = StrQry & " WHERE (ITM.[IC] >= '" & StrIC & "') "

            StrQry = StrQry & " ORDER BY ITM.IC "

            'Session("ItemCode") = DBNull.Value

            AccessDataSource1.DataFile = "C:\mydata.mdb"

            AccessDataSource1.SelectCommand = StrQry

            GridView1.DataSourceID = "AccessDataSource1"

Open in new window

0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:Deadcats
ID: 22725646
sorry one line is commented out

StrQry = StrQry & " WHERE (ITM.[IC] >= '" & StrIC & "') "

that line should not be there.
0
 

Author Closing Comment

by:Deadcats
ID: 31506401
Great help.  Felt Prairiedog went above and beyond.
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22725867
Since you are using DataSource, you can try this:
Dim dv As DataView = CType(AccessDataSource1.Select(
DataSourceSelectArguments.Empty), DataView)
The above line will get the underlying datatable from the AccessDataSource, then you can use it to loop through the data. Let me know if you need more info.
0
 

Author Comment

by:Deadcats
ID: 22725877
I changed the sample you gave in the way that I ususally read the data.  It returns index is out of range.  I know I don't need sessions variables for this but I was just copying code from other pages that I have done.

 If (Me.GridView1.DataKeys(gvr.RowIndex).Value = strIC) Then

this is the line that is giving the error.  

Thank you for all of your help.
Private Sub HighlightRow(ByVal strIC As string)

        Dim id As String

        Dim i As Integer

        Dim strqry As String

        Dim pSize As Integer = Me.GridView1.PageSize

        If GridView1.PageCount = 0 Then

            For Each row As GridViewRow In GridView1.Rows()
 

            Next

        End If

        Session("dbPath") = "C:\mydata.mdb"

        Session("connStr") = "Provider=Microsoft.Jet.Oledb.4.0;" & _

                                           "Data Source=" & Session("dbPath")

        Dim objConn As New Data.OleDb.OleDbConnection(Session("connStr"))

        strqry = "Select * FROM ITM "

        strqry = strqry & " ORDER BY ITM.IC "

        Dim objQry As New Data.OleDb.OleDbCommand(strqry, objConn)

        objConn.Open()
 

        Dim resultQry As Data.OleDb.OleDbDataReader = objQry.ExecuteReader()

        If resultQry.HasRows Then

            Do While resultQry.HasRows = True

                resultQry.Read()

                i = i + 1

                If Not IsDBNull(resultQry.Item("IC")) Then

                    id = resultQry.Item("IC")

                End If
 

                If (id = strIC) Then

                    Me.GridView1.PageIndex = i / pSize

                    Me.GridView1.DataBind()
 

                    For Each gvr As GridViewRow In Me.GridView1.Rows

                        If (Me.GridView1.DataKeys(gvr.RowIndex).Value = strIC) Then

                            gvr.BackColor = Drawing.Color.Yellow

                        End If

                    Next

                    Exit Sub

                End If

            Loop

        End If

    End Sub
 
 

End Class

Open in new window

0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22725891
Modification:
Use this line to get the underlying DataTable:
Dim dt As DataTable = CType(Me.SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataTable)
Then

For i As Integer = 0 To dt.Rows.Count - 1
     dr = dt.Rows(i)
      'Continue
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22725908
Forget about the Session, try this code:
Private Sub HighlightRow(ByVal keyID As Integer)

	Dim id As Integer = 0

	Dim pSize As Integer = Me.GridView1.PageSize
 

	Dim dt As DataTable = CType(Me.AccessDataSource1.Select(DataSourceSelectArguments.Empty), DataTable)

	Dim dr As DataRow

	For i As Integer = 0 To dt.Rows.Count - 1

		dr = dt.Rows(i)

		id = dr("EmployeeID")

		If (id = keyID) Then

			Me.GridView1.PageIndex = i / pSize

			Me.GridView1.DataSource = ds

			Me.GridView1.DataBind()
 

			For Each gvr As GridViewRow In Me.GridView1.Rows

				If (Me.GridView1.DataKeys(gvr.RowIndex).Value = keyID) Then

					gvr.BackColor = Drawing.Color.Yellow

				End If

			Next

			Exit Sub

		End If

	Next

End Sub

Open in new window

0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22725940
Sorry, correction:
Me.GridView1.DataSource = dt   ' not ds
 
0
 

Author Comment

by:Deadcats
ID: 22725960
Thank you again,

I am going to look at this some more later but for right now I got a solution that is pretty fast.  Basically it is what I started with but with your suggestion of going through the table rather than the gridview.  Again, I am sure that this is not the best way but it works.  

I changed it to send in my string because that is what will be typed in before bringing up the gridview.  I don't really need to highlight the field they are looking for but I do need to bring them to the page that item is on.  

Thank you again for all of your help.  I think I have to look at using the Datatable, Dataset, and DataRow but I have to have this done by Friday and am not sure if that will happen if I start looking into that.  

    Private Sub HighlightRow(ByVal strIC As string)

        Dim id As String

        Dim i As Integer

        Dim strqry As String

        Dim pSize As Integer = Me.GridView1.PageSize
 

        Session("dbPath") = "C:\mydata.mdb"

        Session("connStr") = "Provider=Microsoft.Jet.Oledb.4.0;" & _

                                           "Data Source=" & Session("dbPath")

        Dim objConn As New Data.OleDb.OleDbConnection(Session("connStr"))

        strqry = "Select * FROM ITM "

        strqry = strqry & " ORDER BY ITM.IC "

        Dim objQry As New Data.OleDb.OleDbCommand(strqry, objConn)

        objConn.Open()
 

        Dim resultQry As Data.OleDb.OleDbDataReader = objQry.ExecuteReader()

        If resultQry.HasRows Then

            Do While resultQry.HasRows = True

                resultQry.Read()

                i = i + 1

                If Not IsDBNull(resultQry.Item("IC")) Then

                    id = resultQry.Item("IC")

                End If
 

                If (id = strIC) Then

                    Me.GridView1.PageIndex = i / pSize

                    Me.GridView1.DataBind()
 

                    For Each row As GridViewRow In GridView1.Rows()
 

                        For Each cellResult As DataControlFieldCell In row.Cells

                            Dim cellDCF As DataControlField = cellResult.ContainingField

                            Dim cellID As String = cellDCF.HeaderText
 

                            If cellID.ToString = "IC" Then
 

                                Dim cellValue As String = CStr(cellResult.Text)
 

                                If UCase(cellValue) = UCase(strIC) Then
 

                                    cellResult.Visible = True

                                    cellResult.BackColor = Drawing.Color.Aqua

                                    Exit Sub

                                Else

                                    cellResult.BackColor = Drawing.Color.Black
 

                                End If

                            End If

                        Next

                    Next

                    Exit Sub

                End If

            Loop

        End If

    End Sub

Open in new window

0
 

Author Comment

by:Deadcats
ID: 22726035
I know there are some errors in the code above but I have changed them.  

Do While (resultQry.Read())  
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22726067
My code has some error too, sorry. :-(
Basically the DataTable version does not work. You will have to use DataView:

Dim dv As DataView = CType(Me.SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
But, I am glad you get it working now.
0
 

Author Comment

by:Deadcats
ID: 22726145
Thanks again.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

What is Node.js? Node.js is a server side scripting language much like PHP or ASP but is used to implement the complete package of HTTP webserver and application framework. The difference is that Node.js’s execution engine is asynchronous and event…
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now