Fixing SharePoint error: No item exists at [url]?ID=n. It may have been deleted or renamed by another user

Yesterday I was creating a page in SharePoint Designer and on testing got a server error:

No item exists at http://sharepointsite/WebPages/My-Page?ID=56.  It may have been deleted or renamed by another user.

I’d got code in the page that examined the ‘ID’ QueryString parameter and tried to load that item from a particular list.  This same code was working on another page.

This MSDN article described the problem,

This problem happens because Sharepoint has its own variable named ID 
which it uses to identify documents/pages on the server. Our solution 
should not be using a variable named ID.

I changed my QueryString parameter to RequestID instead and all was good, apart from the thought of why the other page still worked fine. 

I then realised that if it didn’t know what list it was trying to target, then the ‘List’ querystring parameter needs to be there too – as per other ‘application page’ requests in the _layouts folder, like approve/reject.

It then became obvious that I was doing too much work anyway:

Passing in the List as well as the ID allows you to then just get straight to the list item with the following code…

        SPListItem item = (SPListItem)SPContext.Current.Item;

as the List and ID are already taken care of.  A little neater than what I ‘was’ doing….

        SPListItem currentItem = null;

        //Get ID and List Item information
        requestList = SPContext.Current.Web.Lists["My List"];        
        if (requestList != null && Request.QueryString["ID"] != null)
        {
            if (int.TryParse(Request.QueryString["ID"].ToString(), out requestID))
            {
                //Get Item
                currentItem = requestList.GetItemById(requestID);


            }
            
        }

This code’s still fine (apart from the querystring ‘ID’ name) if you need to load an item from a list that you don’t know the guid for at the time.