How do I display data in a datagrid specific to the logged in user using the User ID

Hi,

I've got a table that holds user details (such as age, location etc). This table is linked to a user logon details table by the UserID column.

How do I get a datagrid to display the logged on users details?  Everything I've read so far uses Username but username isn't a column in my UserDetails table.

I've tried SELECT all from the user details table and using UserID as a session parameter but the datagrid doesn't display so I'm doing something very wrong I think.

The sql statement looks like this:

 SELECT UserID, FirstName, Surname, Telephone, Section, Location FROM dbo.aspnet_UserDetails WHERE (UserID = @UserID)

Parameter Source is set to "Session"
SessionField is set to "UserID"

Using Visual Web Developer 08 Express 

Any advice appreciated.
Thanks

0
dotnetnoob101
5/22/2008 1:45:43 PM
asp.net.object-datasource 16182 articles. 0 followers. Follow

25 Replies
1124 Views

Similar Articles

[PageSpeed] 19

Get the UserID of the currently logged-in user like so: 

MembershipUser user = Membership.GetUser();

if (user != null)
{
	Guid userID = new Guid(user.ProviderUserKey.ToString());
}

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
5/22/2008 2:49:55 PM

Thanks for responding, I will give this a go.

0
dotnetnoob101
5/22/2008 3:29:32 PM

Sorry I really am new to all this.  Where would I put that code?  Does it go in the code behind page of the page where I'm placing the datagrid?

 Sorry, I know this is really basic stuff  Embarrassed

0
dotnetnoob101
5/27/2008 10:41:12 AM

Thanks for the links.  I've set up my registration page and my login page and it all works excellently.  I tend to arrive at problems though when I try to do something thats not always explained in the walkthroughs and examples, something that seems a little too specific to what I'm trying to do. I'm finding the forums really helpful though as they tend to focus on specific issues

0
dotnetnoob101
5/27/2008 11:07:08 AM

If you're using a SqlDataSource, use the Selecting event handler of that control like so: 

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
	MembershipUser user = Membership.GetUser();

	if (user != null)
	{
		e.Command.Parameters["@UserID"].Value = user.ProviderUserKey;
	}
}

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
5/27/2008 12:11:52 PM

Ok thanks for that, yes I'm using a SqlDataSource so I've put that code into the code behind page (converted to VB.Net)

Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceSelectingEventArgs)
    Dim user As MembershipUser = Membership.GetUser()
   
    If user IsNot Nothing Then
        e.Command.Parameters("@UserID").Value = user.ProviderUserKey
    End If
End Sub

The datagrid still doesn't display though - do I need to reconfigure my data source as it is still as follows:

 SELECT UserID, FirstName, Surname, Telephone, Section, Location FROM dbo.aspnet_UserDetails WHERE (UserID = @UserID)

Parameter Source is set to "Session"
SessionField is set to "UserID"

I've tried different parameters etc but the datagrid doesn't display (presumably because it can't get any values so doesn't display anything)

0
dotnetnoob101
5/28/2008 8:57:24 AM

Let me see your SqlDataSource code.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
5/28/2008 11:59:20 AM
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                       
ConnectionString="<%$ ConnectionStrings:aspnetusersConnectionString3 %>"

SelectCommand="SELECT UserID, FirstName, Surname, Telephone, Section, Location FROM dbo.aspnet_UserDetails WHERE (UserID = @UserID)">

<SelectParameters>
<asp:SessionParameter Name="UserID" SessionField="@UserID" />
</SelectParameters>
</asp:SqlDataSource>

0
dotnetnoob101
5/28/2008 12:09:19 PM

Are you really storing your Session variable like so?

Session["@UserID"] = ???

Make sure the SessionField matches what key you're really using for the Session object.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
5/28/2008 12:24:24 PM

I wasn't sure what that was doing to be honest - should I be even using that?  I added it because I was reading about it on a different site and thought it might help with the problem I'm having.

0
dotnetnoob101
5/28/2008 1:03:46 PM

I'm not sure, you tell me. Are you passing in the UserId from another page via the Session object? We really need to see your relevant code front and back to see what's going on.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
5/28/2008 1:16:16 PM

Basically I've set up the registration pages using the standard Login controls. I've then customised it slightly by adding a new CreateUserWizardStep to capture a few other details.  These other details are held in a separate table linked by UserID to the standard aspnet_Users table.  To do that I used this:

Protected Sub CreateUserWizard1_CreatedUser1(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreateUserWizard1.CreatedUser

Dim UserNameTextBox As TextBox = DirectCast(CreateUserWizardStep1.ContentTemplateContainer.FindControl("UserName"), TextBox)
Dim DataSource As SqlDataSource = DirectCast(CreateUserWizardStep1.ContentTemplateContainer.FindControl("InsertExtraInfo"), SqlDataSource)
Dim User As MembershipUser = Membership.GetUser(UserNameTextBox.Text)
Dim UserGUID As Object = User.ProviderUserKey

DataSource.InsertParameters.Add("UserId", UserGUID.ToString())
DataSource.Insert()

End Sub

I then have a page set up in a folder called MemberPages that only logged in users can access - I believe this is just standard stuff - i.e. I've not done anything special and I've just followed the walkthroughs included in Visual Web Developer Express so I've used the Web Site Admin Tool to deny anonymous access to this folder.  Its in this folder where the page sits where I want to display the fields dependant on the logged on UserID.

As I've just followed the walkthrough using the wizards and standard controls I'm not sure what is being passed through.  I can write out the logged in username and that displays ok: <asp:LoginName ID="LoginName1" runat="server" />

so the login process works fine and I assumed the LoginName would be held as a session variable.  But aswell as LoginName I want to incorporate UserID in order to display the users other details.

 Thats really all there is to it as far as coding is concerned.  I appreciate your help so far by the way, you've been very patient! Smile

0
dotnetnoob101
5/28/2008 1:54:18 PM

You should then be able to retrieve the user's ID via the Membership object as I described previously.

ASPX 

<asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:aspnetusersConnectionString3 %>"
	selectcommand="SELECT UserID, FirstName, Surname, Telephone, Section, Location FROM dbo.aspnet_UserDetails WHERE (UserID = @UserID)" 
	onselecting="SqlDataSource1_Selecting">
	<selectparameters>
		<asp:parameter name="UserID" />
	</selectparameters>
</asp:sqldatasource>

CODE-BEHIND 

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
	MembershipUser user = Membership.GetUser();

	if (user != null)
	{
		e.Command.Parameters["@UserID"].Value = user.ProviderUserKey;
	}
}

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
5/28/2008 2:05:58 PM

Thanks you're an absolute star, thats working great!

0
dotnetnoob101
5/28/2008 2:14:31 PM

Taking this a little further then, how would I go about inserting the UserID value into another table to tie up records to UserID?

 So I have Table1 that contains the UserID primary key field (which we played around with earlier via SqlDataSource1) and I also have Table2 that contains User Details (which is now displaying great on my DataGrid) and I now also want Table3 to contain UserID as a foreign key.

So on the page that I have my DataGrid and SqlDataSource1 I also have a form that needs to be able to insert the UserID value into Table3 so Table3 can be referenced by UserID. Is this possible? I have an Insert statement in the code-behind page but I can't figure out the syntax to add UserID to my Insert statement Sad

 Thanks.

0
dotnetnoob101
6/3/2008 1:36:39 PM

You'd pretty much do it exactly the same way except you'd use the SqlDataSource.Inserting event handler instead. Obtaining the currently logged-in user's ID can be done exactly the same way as I showed you before.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
6/3/2008 1:48:57 PM

Great, thanks again for your help! Smile

0
dotnetnoob101
6/3/2008 3:00:24 PM

Thanks for the thread on this, and Ed...thanks for the solution.  I was having the exact same issue today.  I was using the code to get the UserID, but it wasn't being recognized by my datagrid.  "onselecting="SqlDataSource1_Selecting" was what I was missing.

THANKS!

0
LordOfTheBathtubRing
6/4/2008 5:57:53 PM

im pretty new at this, and am kinda stuck

i got the above example working with c# but am trying to do it in vb as that is what the rest of my site is in but i'am getting nowhere
if someone could help with a vb translation it would be much appreciated .

 
cheers
 

0
radface
10/30/2008 5:41:02 AM

Hi radface, this is the vb I've been using:

 Protected Sub SqlDataSource1_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs)
    Dim user As MembershipUser = Membership.GetUser()
   
    If user IsNot Nothing Then
        e.Command.Parameters("@UserID").Value = user.ProviderUserKey
    End If
End Sub

Also, you may find this conversion site helpful:

http://www.developerfusion.com/tools/convert/csharp-to-vb/

0
dotnetnoob101
10/30/2008 8:26:44 AM

Thankyou

that works perfectly.
will keep that code converter in mind aswell.
could come in very handy in the future.

cheers
 

0
radface
10/30/2008 10:36:02 PM

I have a little problem with this...my datagrid comes up but it displays all the data not just for the person logged in.

Got any ideas?

source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="userdetails.aspx.cs" Inherits="userdetails" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

 

<asp:GridView ID="GridView1" runat="server" AllowSorting="True"

AutoGenerateColumns="False" DataKeyNames="Serial_number"

DataSourceID="SqlDataSource1">

<Columns>

<asp:BoundField DataField="Serial_number" HeaderText="Serial_number"

ReadOnly="True" SortExpression="Serial_number" />

<asp:BoundField DataField="ESP_date" HeaderText="ESP_date"

SortExpression="ESP_date" />

<asp:BoundField DataField="Model_number" HeaderText="Model_number"

SortExpression="Model_number" />

</Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

onselecting="SqlDataSource1_Selecting"

SelectCommand="SELECT [Serial_number], [ESP_date], [Model_number], [UserId] FROM [product_info]">

<SelectParameters>

<asp:ControlParameter ControlID="GridView1" Name="UserId"

PropertyName="SelectedValue" />

</SelectParameters>

</asp:SqlDataSource>

 

</div>

</form>

</body>

</html>

 

sql code behind:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)

{

MembershipUser user = Membership.GetUser();if (user != null)

{

e.Command.Parameters[
"@UserId"].Value = user.ProviderUserKey;

}

}

Thanks

0
nkair19
2/6/2009 7:50:33 PM

Not sure tbh.  I use vb.net and not C# but there doesn't seem to be much difference between the vb and c# code except the Handles clause in vb. This isn't supported in c# as far as I'm aware so I'm not sure what the equivalent would be or whether it should work anyway without a Handles clause. Maybe any c# experts out there can advise.

0
dotnetnoob101
2/12/2009 9:20:55 AM

nkair19:

I have a little problem with this...my datagrid comes up but it displays all the data not just for the person logged in.

Got any ideas?

source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="userdetails.aspx.cs" Inherits="userdetails" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title> </head>

<body>

<form id="form1" runat="server">

<div>

 

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Serial_number"

DataSourceID="SqlDataSource1">

<Columns>

<asp:BoundField DataField="Serial_number" HeaderText="Serial_number"

ReadOnly="True" SortExpression="Serial_number" />

<asp:BoundField DataField="ESP_date" HeaderText="ESP_date"

SortExpression="ESP_date" />

<asp:BoundField DataField="Model_number" HeaderText="Model_number"

SortExpression="Model_number" />

</Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

onselecting="SqlDataSource1_Selecting"

SelectCommand="SELECT [Serial_number], [ESP_date], [Model_number], [UserId] FROM [product_info]">

<SelectParameters>

<asp:ControlParameter ControlID="GridView1" Name="UserId"

PropertyName="SelectedValue" />

</SelectParameters>

</asp:SqlDataSource>

 

</div>

</form> </body>

</html>

 

sql code behind:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)

{

MembershipUser user = Membership.GetUser();if (user != null)

{

e.Command.Parameters[
"@UserId"].Value = user.ProviderUserKey;

}

}

Thanks

First off, you should be using a Parameter as opposed to a ControlParameter. Secondly and most importantly, you don't have a WHERE clause in your SQL statement so there's no way to filter your results to just that user.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
2/12/2009 1:09:47 PM
Reply:

Similar Artilces:

Logged in user displays user specific data from database
Hi there - I am fairly new to ASP.NET and am hoping for some guidance here ... I am building an application for manages to track employees as the employee leaves the business.  Basically there are processes a line manager is required to complete and I want the manager to enter completion dates when those processes have been completed. I have gotten as far as successfully creating the login/membership controls.  The user (line manager) logs in and is then redirected to the correct page and thats fine.  However, I then want for the user to see records from a dat...

Display data in a datagrid that is specific to only the logged in user
How do you display data from tables that is based on the logged in username.  I know that some post are saying to use the "GetUser" method via Membership.  Like for example, I want to display all vendor information for a specific vendor that has logged onto the application in a datagrid?  The username in the database is the same as the VendorID.  I'm using Visual Studio 2005 and a SQL Server 2005 database.   Any feedback would be greatly appreciated. Thanks, rsandes2 (Still a newbie) Hi, If your users are logging into website and the login name m...

display data for a particular logged in user (User.Identity.Name;)
hi, basically i have a database table with: fileNo, fileName, fileSize, fileType, fileOwner etc at the minute my grid view displays ALL files for every fileOwner, how does one filter this to only displaying the files which belong to a particular fileOwner who is logged in.. i.e. SELECT * FROM tblFile       WHERE fileOwner = (User.Identity.Name)         -   to show files for a user who is logged in   how does one do this please?   thanks and regards Hi,jules U can Do like thisI am assuming that ur ...

how to get user data from a logged in user
I have the standard login controls from ASP.NET 2.0 on my site. Now i've added a id field from another table to the aspnet_users table as FK. Now i want to use this ID (if the user is logged in) to populate my datagrid. How can i get this ID?  Erik    Check below link Work With Membership API HCHaissam Abdul MalakMCAD.NET| Blog | Hi Please follow the link http://forums.asp.net/thread/1702250.aspx and raise the problem you've meet :) Good luckBest RegardsXiaoYong DaiMicrosoft Online Community SupportPlease remember to click “Mark as Answer” on the ...

how to get the user id of the currently logged in user?
hi,       m develoing a site whereby employees are supposed to log in and take orders.  the users are being created thru the ASP web Administration tool and stored by default into the SQL Server Database named AspNetDB.mdf that's stored in the App_Data folder of our website. the database is created auomatically. How to display the userid as this userid is too complicated and there can be many users with the same username. You can use the Membership class to get the info about a user: Membership.GetUser() The GetUser method can also take a username as a...

displaying user information to currentlt logged in user
Hi I have created a database which stores user details like name address, intrests, occupation etc on setting up a new account. I would now like to create a user profile page that would display the currently logged on user information and allowthat user to view his account informatioon and edit if needed. There is the data grid view I could use but how do i set it up to recognise which user is logged on and retrive the relevant details.  Users should be able to edit their details when edit is clicked. Also each set of details is stored in different tables e.g YOUR PROFILE Name: John ...

Searching user table using user ID
 I know I can access the currently logged in user id using this MembershipUser currentUser = Membership.GetUser();done using asp.net sql provider, in c#  say I know the user ID of a certain user, and I want to use this ID to search anoter table and return a string for the home address corresponding to that user ID, how do I do it? thx. use this:SELECT     UserNameFROM         aspnet_UsersWHERE     (UserId = @user) Regards,Stefan Uzunov Hi there, You already have the user, try to&n...

Loop email to each user with user specific data
I am trying to figure out how to generate and send an email to all customers in a database with their respective order information - I have a control (autofire) that will ensure the scheduleing and auto-execution but need a way to loop through all the order records related to a customer and fire off an email with all order data associated with their account to them? check out System.Web.Mail...

Users logging in as the same user..
HI there.. I have a problem with ASE12.0 .. I have created 10 users on the database and granted everybody permissions and all.. However, it seems everybody, no matter who logs in, logs in as the same user.. For eg... I have user logins John, Alex, Alan, Steve......etc etc And i created a user group for all of them (eg developers..) However, when they log on to isql, anything that they do will be under John, no matter if it is logins John, Alex, Steve... or etc etc.. If i do a sp_who.. all the connections will be listed as John. If they create tables, all table created will ...

how to create a user object in a user object
how to create a user object in a user object dynamically ? I want create an object row focus indicator (p_focusindicator), in an userobject datawindow. But i use in userobject datawindow this code: ip_focusindicator = create p_focusindicator SetRowFocusIndicator(ip_focusindicator) Do you know the solution ? Thanks Mikael You're in the wrong newsgroup. This a PowerDesigner newsgroup not a PowerBuilder newsgroup. You want to be in powersoft.public.powerbuilder.general With that being said, I do know the answer to your questions. First off, you cannot create a us...

Placing user objects on to other user objects.
Hello, Can anybody tell me why I'm not able to use syntax like openuserobject to connect an object to another object. You can attach user objects to a window, but can you attach a user object to another user object? BTW, nobody knows any good 3D drawing ActiveX's out there??? Mark Schupay Schupay Software Design 724-453-1331 ssd@zoominternet.net OpenUserObject() is a window (and all PB descendants thereof), not a system or WIndowObject function. That's the technical reason anyway. However, there is a method of doing this. Also, you may need to add the ...

Display data for logged in User only
I try to figure out how to display data which belongs to one individual User only.Once the User logged in, he should see only the data which is related to his UserId. Currently I'm usingSELECT aspnet_Customers.FirstName, aspnet_Customers.LastName, aspnet_Customers.Address, aspnet_Customers.ZipCode, aspnet_Customers.City, aspnet_Customers.Country, aspnet_Customers.CustomerID, aspnet_Customers.UserID, aspnet_Membership.LoweredEmail, aspnet_Membership.LastLoginDate FROM aspnet_Customers INNER JOIN aspnet_Membership ON aspnet_Customers.UserID = aspnet_Membership.UserIdTwo Questions:1....

Display data for Logged in user
 Hi, I am trying to show data from a database where one of the DB field values matches the name of the logged in user. I have LoginName control on the same page so I only want to display data that has a matching value in the DB field.Hope that makes sense? Thanks Here is what you can do: Dim uname as String = user.identity.name if user.identity.isauthenticated then sqlcmd="SELECT * from db_base Where username='" & uname & "' " then execute the sqlcmd that is itFun begins at http://www.ovbet.comNow...From the first humanplace &n...

Display data for logged in User only
I try to figure out how to display data which belongs to one individual User only.Once the User logged in, he should see only the data which is related to his UserId. Currently I'm usingSELECT aspnet_Customers.FirstName, aspnet_Customers.LastName, aspnet_Customers.Address, aspnet_Customers.ZipCode, aspnet_Customers.City, aspnet_Customers.Country, aspnet_Customers.CustomerID, aspnet_Customers.UserID, aspnet_Membership.LoweredEmail, aspnet_Membership.LastLoginDate FROM aspnet_Customers INNER JOIN aspnet_Membership ON aspnet_Customers.UserID = aspnet_Membership.UserIdI know there is somethi...

Web resources about - How do I display data in a datagrid specific to the logged in user using the User ID - asp.net.object-datasource

Want to preview our new DataGrid for Xamarin.Forms?
tl;dr Zumero.DataGrid is a Xamarin.Forms control for displaying data in rows and columns. If you would be interested in testing and previewing ...

Mad King DataGrid
This post is about scrolling in WPF and the egocentric DataGrid control. I’ll give the project background but if all you’re interested in is ...

Stack Overflow
Stack Exchange log in - careers - chat - meta - about - faq Questions Tags Users Badges Unanswered Ask Question Top Questions interesting 295 ...

Microsoft Silverlight - Wikipedia, the free encyclopedia
Microsoft Silverlight is an application framework for writing and running rich Internet applications , with features and purposes similar to ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Casaba Security » Products » X5s Testing Tool For Finding XSS Vulnerabilities
Security analysis, consulting, development and testing partners who understand your business strategy.

CodeGuru - Microsoft developers related ideas, articles, tips, tricks, comments, downloads, and so much ...
CodeGuru is where developers can come to share ideas, articles, questions, answers, tips, tricks, comments, downloads, and so much more related ...

Caliburn Micro: WPF, Silverlight, WP7 and WinRT/Metro made easy.
A small, yet powerful framework designed for WPF, Silverlight and WP7. It implements a variety of UI patterns for solving real-world problems. ...

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 11 Jul 2012

license-discuss@opensource.org: 11636: first draft of license proliferation committee report
FYI,the first draft report of the OSI's License Proliferation Committee.To join the OSI's license proliferation discuss email list, send anemail ...

Resources last updated: 12/18/2015 12:56:28 AM