0

When I login I want to display the image of user.
I use Rows[0] but when i change the user that is at row[1] it shows me the row[0] image.
How do i implement a code to switch the rows and know what user is logged on.
I am a beginner here, so take it slow.

`C#

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["Username"] != null)
    {
        String a = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
        using (SqlConnection con = new SqlConnection(a))
        {
            DataTable dt = new DataTable();
            SqlDataAdapter comanda = new SqlDataAdapter("SELECT *FROM Register", con);
            comanda.Fill(dt);


            if (dt.Rows.Count > 0)
            {
                emailutilizator.Text = dt.Rows[0]["Email"].ToString();
            }

            if (dt.Rows[0]["ImageData"].ToString().Length > 1)
            {
                 Image1.ImageUrl = dt.Rows[0]["ImageData"].ToString();
            }
            else
            {
                 Image1.ImageUrl = "~/images/defaultuserimg.png";
            }
        }`   
    }

The database looks like this

`Tabel

CREATE TABLE [dbo].[Register] (
    [Uid]       INT            IDENTITY (1, 1) NOT NULL,
    [Username]  NVARCHAR (MAX) NULL,
    [Email]     NVARCHAR (MAX) NULL,
    [Password]  NVARCHAR (MAX) NULL,
    [ImageData] NVARCHAR (MAX) NULL,
    PRIMARY KEY CLUSTERED ([Uid] ASC)
);
`

[The information from database] [enter image description here]2

GuidoG
  • 11,359
  • 6
  • 44
  • 79
Daniel
  • 99
  • 9
  • It looks like you need the current user. You're making a comparison on the imagedata length, but only doing it on row0 which will be the image for the user on row0. You need to find out which row the current user is. With that data, you should also narrow down your SQL statement, try looking at the answer to this question: http://stackoverflow.com/questions/19078072/best-way-to-protect-against-sql-injection-in-sqldataadapter – Robbie Dec 02 '16 at 14:14

2 Answers2

2

You are getting all the rows with

SELECT * FROM Register

but then always selecting the first row Row[0].

You should change it to

SELECT * FROM Register WHERE Username = ' + Session["Username"] + '

That way you will only get one row so selecting it with Row[0] will be fine.

... but don't do it exactly like that, as its open to SQL injection attacks. See What are good ways to prevent SQL injection?

Community
  • 1
  • 1
James Casey
  • 2,447
  • 1
  • 11
  • 19
1

First, in your SQL statement use a WHERE condition to bring back the user who is logged in. e.g.

SqlDataAdapter comanda = new SqlDataAdapter("SELECT * FROM Register WHERE Username=@username", con);
comanda.SelectCommand.Parameters.AddWithValue("@username",Session["Username"]);

Then you can always use row[0] as it will only return the current user.

This solution includes SQL injection protection.

Robbie
  • 327
  • 1
  • 4
  • 13