user1625271
user1625271

Reputation: 123

not being able to display the current user details using sql in vb.net

I have used an sql statement where I want to display the details of the current user that is logged in. But when I run this command it

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

SelectCommand = "SELECT *  FROM member WHERE username = 'User.Identity.Name'"

it does not show any details but when I run

SelectCommand = "SELECT *  FROM member WHERE username = 'david'" 

the username david exists in the database and displays the details of only david in the web form. I even did Response.Write on the User.Identity.Name and that statement displays the current user that is logged in the page.

Upvotes: 0

Views: 1086

Answers (1)

Alex R.
Alex R.

Reputation: 4754

The issue is you're passing the actual User.Identity.Name as string instead of its value.

SelectCommand = String.Format("SELECT *  FROM member WHERE username = '{0}'", User.Identity.Name)

But the better (and safer) practice would be something like

SelectCommand = "SELECT *  FROM member WHERE username = @UserName"
SelectCommand.Parameters.AddWithValue("@UserName", User.Identity.Name)

This will prevent SQL injection.

EDIT: Since you are defining this in your page, you can use the following template:

<asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:Details %>" SelectCommand="SELECT * FROM members WHERE ([username] = @UserName)">
    <SelectParameters>
        <asp:Parameter Name="UserName" Type="String" DefaultValue="" />
    </SelectParameters>
</asp:SqlDataSource>

Then set the default value to User.Identity.Name on the server side:

SqlDataSource1.SelectParameters.Item(0).DefaultValue = User.Identity.Name

The easier way to do this is by using the Configure Data Source wizard, which is available by clicking the right arrow beside the SqlDataSource object in design view.

Upvotes: 2

Related Questions