Hi I am having a problem when trying to update my datagrid view so that it displays only the data of the user who is logged in.
I have two tables, one called records and one called users. The users table contains user data including username and user id. the records table contains user id as a foreign key and data about bmi readings.
I have a login page which when logged in displays a message which is welcome (username)
This is the code I have written to update the datagridview
SqlConnection con = new SqlConnection(@(removed to simplify));
con.Open();
var sda = new SqlDataAdapter("SELECT * FROM Records WHERE UserID=@UserID", con);
sda.SelectCommand.Parameters.AddWithValue("@UserID", currentUsernameLabel.Text);
DataSet DATA = new dataGridView.DataSource =
con.Close();
How do I look up what the userID is, (based on the username which is stored in currentUsernameLabel.Text) so that I can add it as a parameter?
EDIT: these are my tables:
Records table
Users table
Please let me know if you need anymore information in order to help
EDIT:
I have come up with the following solution:
//Find ID of user who is logged in
string currentUserID;
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True");
SqlCommand command = new SqlCommand("select UserID from Users where Username = '"+currenUsernameLabel.Text+"' ", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
currentUserID = reader["UserID"].ToString();
command.Parameters.AddWithValue("@CurrentUserID", currentUserID);
command.ExecuteNonQuery();
}
reader.Close();
} catch (SqlException ex)
{
MessageBox.Show(ex.Message);
} finally
{
conn.Close();
}
//update datagridview
this.recordsTableAdapter.ChartAll(this.recordsDataSet.Records);
}
The ChartAll query is as follows:
SELECT Height, Weight, BMI, Date FROM dbo.Records
WHERE UserID = @CurrentUserID
The error message is : Error message
Has it got something to do with needing the parameter to be an int not a string?
var table = new DataTable("myTable");
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString))
{
using (var da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand("SELECT * FROM Records", con);
da.Fill(ds, "Records");
}
}
dataGridViewPerson.DataSource = table.DefaultView;
get your connectionstring from the config file, change the code to match your code, otherwise you wont learn. aka use and fill a DataTable
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.