get current logged in user asp

I have the following code written in VB. Which grabs hold of the current logged in user and assigns it to a string.

I need to do something similar but in C#. I have a page which is going to populate a gridview depending on the currently logged in user. but for the life of me i cant find a away to assign the current logged in username to a variable.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cusername As String
        If HttpContext.Current.Request.IsAuthenticated Then
            cusername = HttpContext.Current.User.Identity.Name        End If
        SqlDataSource1.SelectCommand =  select * from  aspnet_membership where email = '" & cusername & "' 
    End Sub
End Class

Open in new window

Who is Participating?
OBonioConnect With a Mentor Commented:
Just change the first line.

string cusername = string.Empty;

Open in new window

Refael AckermannCommented:

String cusername = (HttpContext.Current.Request.IsAuthenticated) ? HttpContext.Current.User.Identity.Name : null;

Open in new window

The c# version is below. You were missing quotes at the beginning and end of the sql statement.

You might want to check if your code is going into the if statement.

string cusername;
        if (HttpContext.Current.Request.IsAuthenticated)
            cusername = HttpContext.Current.User.Identity.Name;
        SqlDataSource1.SelectCommand = "select * from  aspnet_membership where email = '" + cusername + "'";

Open in new window

leap29Author Commented:
hi im now getting the following compilation error??

Use of unassigned local variable 'cusername'
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.