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?
The correct solution for this is going to vary a bit depending on how you are actually pulling the data from the database. But the process is pretty much the same.
Now, the kicker here is step 1 and 2. if you are paging the data at the SQL level, you will need to get another stored procedure/database call to determine the "row id" of the selected item. Otherwise, if you are loading to a object collection, or a dataset, you can loop through and find the item. Keeping a row counter if you really must.
Not elegant, but honestly there isn't an "elegant" way of doing this.
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:
@Brian if I'm correctly understanding your question you mean that you have everything wired up it user clicks on a row when the page is showing. You want that if somebody types the URL of page directly in browser and appends ?id=x to it, you should direct him to relevant page, select relevant row and populate FormView based on selected record.
Well if this is the case I've made something, but let me warn before hand it is not very elegant and its 2:30 AM here so please don't laugh.
Assumption:- In presented solution the DataKeyNames field is set to Primary Key of the source table. The rows fetched are sorted by this key. I'm using SubSonic 3 for talking to SQL Server 2005 Express DB (coincidently this is my first SS3 project, very busy at office to try it).
The table definition is as follows:
The aspx:
C# Code (Hold your laughs):
PS:- It is failing if you put id of last record.
EDIT:- Here is link to Project
The Data Access tutorials on ASP.NET touch on aspects of your question. It's been a while for me, but I think that the last part of this particular tutorial maybe the closest to what you need:
http://www.asp.net/learn/data-access/tutorial-10-vb.aspx
Just turn on paging for the GridView and everything should just work.