Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

Datagrid Tidbit Refactored
By David Reed

Alvin had a good start in his article, but the recommendations in it are NOT ideal from a usability perspective, IMNSHO. However, his basic suggestions are better than errors in production. Heh.

This way the user gets the functionality of stepping backward through the pages instead of having to start all over on Page 01 every time the page count shifts unexpectedly.

Because the HttpException with the message "Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount." usually happens when the user is allowed to delete records from the results set on the fly (or in high concurrency apps where other users can affect the results set underneath you), what is ideal is the following refactor:

  1. Create a single method for popping the grid (ex, PopGrid(...) ) in all cases. Always a good idea anyway.
  2. Inside PopGrid(), recurse when this specific error occurs:
        // UNDONE: Implement whatever method signature you need for popping activities.    
        private void PopGrid( ... )
        {
            // UNDONE: Implement data loading and other filtering.
    
            try
            {
                dgList.DataBind();
            }
            catch( System.Web.HttpException ex ) // We don't want *every* HttpException, though.
            {
                /*
                * This way we just get the one that we want, but it's -1 because
                * it will break if M$ ever changes the string that distinguishes the error.
                */
                if( ex.Message == "Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount." _
                    && dgList.CurrentPageIndex > 0 )
                {
                    dgList.CurrentPageIndex--;
                    PopGrid();
                }
                else
                {
                    // Throw back all the errors that are too small for us to care about. ;)
                    throw;
                }
            }
        }
    
  3. This method will just backpedal through the pages as the user deletes items from the grid.
  4. The nasty error will only bubble when the CurrentPageIndex is set below 0 intentionally.

Strong Warning: If you have a potentially LARGE number of pages (more than 20 or so) or a high concurrency app (or both), I would strongly consider NOT using this method.