Showing only the logged-on user's data
This tutorial explains how to display data associated only with the logged-on
user from a membership-based, database-driven website using, for example, a
Gridview.
The tutorial assumes you have used the controls associated with the Login and
Membership features of asp.net to create and add users to your website, in which
case the ASPNETDB.MDF membership database has been created, and it contains an
ASPNET_USERS table which associates each user with a unique UserID.
It further assumed that any table you wish to draw data from has User_ID as a
foreign key (associated with UserID of the aspnet_users table) so that we may
use it in the WHERE clause of the GridView from which we will be drawing the
user's data. Readers who do not know what a foreign key is should read
database tutorial #11 on this site for assistance in understanding how a relational database is set up.
1. On any aspx page where you wish to bring up data associated with the logged
on user, drag a label control onto the page and give it the ID of
"LblUserIDValue". Set its visibility property to "False" since there is no need
to actually show the UserID.
2. Place a Gridview on the page, and follow along the steps of tutorial2 on this
website -- choosing or creating the sqldatasource, the fields of interest, etc
-- to bring up the data you are interested in, making sure the field containing
the User_ID is among the chosen.
3. At this point the Gridview will show all users data; we now need to modify
things so it shows only the logged-on users data.
4. First we must add the following code when the page loads, which assigns the
logged-on user's UserID to the label we created in step 1:
LblUserIDValue.Text = Membership.GetUser().ProviderUserKey.ToString()
The best way to do this us use Visual Web Developer Express
(see tutorials #11 and #13 on this site for some discussion on VWD). If, in design view, you simply double
click in a blank spot on your page, VWD will automatically take you to the page
load event of the VB code-behind page, where you will need to put the above line
of code.
5. In design view of the page, click on the sqldatasource that is driving your
Gridview. In the properties pane, click on the select query, and then the little
square expander box to display the command and properties editor for the query.
6. Click on the Add Parameters button. for the Parameter Source choose Control,
and for the ControlID choose LblUserIdValue.
7. IMPORTANT STEP: Go into source code view of your aspx page. Everywhere you
see the phrase Type="Object" associated with User_ID you *must* delete that
phrase. Otherwise the page will throw an error when it is run.
Now the only data showing in the gridview should be that of the logged-on user.
If you have not done so, you may want to edit the User_ID column in the GridView
so that it is not visible.