Olga
Olga

Reputation: 117

How to display data based on current logged user?

How do you display data that is retrieved from database according to the current login user? I know that I should declare the id, but I don't really know how...

I have 2 tables in SQL.

User:

ID || Name || Last_Name || date ||

List

ID || Product || description || user_id

private void BindGridView()
    {  
string constr = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(constr))
            {

                using (SqlCommand cmd = new SqlCommand())
                { 
                    cmd.Connection = conn;
                    cmd.CommandText = @"SELECT * From List where ID = @ID";
                    cmd.Parameters.AddWithValue("@ID", ?);

                    using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        ad.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }     
        }
    }

Upvotes: 0

Views: 2763

Answers (1)

Usman
Usman

Reputation: 4703

according to your table the query should be

select * from list where user_id = id

here id is the userid passed to the method

e.g private void BindGridView(int id)

another way is to use session

and to store id after login you have to store it in session

session["UserId"] = userid;

and you can use it in function like

int userid = Convert.ToInt32(session["UserId"]);
cmd.CommandText = "SELECT * FROM list where user_id = " + userid + "";

and also dont forget to use conn.Open() and conn.Close() after executing query

Upvotes: 1

Related Questions