GridView in ASP.Net -- Selecting the correct row

asp.net, gridview

Solution

If you set the DataKey field of the GridView to contain the primary key, there is this CodeProject article on how to set the selected index of a gridview, based on the key value of the record, using an extension method:

public static void SetRowValueValueByKey(this GridView GridView, string DataKeyValue)
{
    int intSelectedIndex = 0;
    int intPageIndex = 0;
    int intGridViewPages = GridView.PageCount;

    // Loop thru each page in the GridView
    for (int intPage = 0; intPage < intGridViewPages; intPage++)
    {
        // Set the current GridView page
        GridView.PageIndex = intPage;
        // Bind the GridView to the current page
        GridView.DataBind();
        // Loop thru each DataKey in the GridView
        for (int i = 0; i < GridView.DataKeys.Count; i++)
        {
            if (Convert.ToString(GridView.DataKeys[i].Value) == DataKeyValue)
            {
                // If it is a match set the variables and exit
                intSelectedIndex = i;
                intPageIndex = intPage;
                break;
            }
        }
    }

    // Set the GridView to the values found
    GridView.PageIndex = intPageIndex;
    GridView.SelectedIndex = intSelectedIndex;
    GridView.DataBind();
}

Problem

I have a page that includes a GridView in it. That GridView is paged with 10 items at a time. Normally, I want the user to select the item from the GridView and populate the FormView. This works well. I also want to support a query parameter ?ID=n where the page will load the specified item. How do I tell the DataGrid or the data source which item to set as the data context? I want the DataGrid to go to the proper page and select the item, showing the specified item in the FormView. I can't figure out how to do this other than limiting the data source to the specific item, which is confusing to the user. Any thoughts?

Original source