I want to write a code, which makes only currently logged in user able to update data i DataGridView using only his ID, which he has to write in textBox1,press the button and thus update data in selected row. Right now currently logged in user can also update data in DataGridView using other user's ID, which should not be possible. I have tried this code:
private void button5_Click(object sender, EventArgs e)
{
string ID = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (textBox1.Text == "" || textBox1.Text != ID)
{
MessageBox.Show("Insert your ID and try again.");
}
else
{
try
{
String ConnectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True";
SqlConnection myconnection = new SqlConnection(ConnectionString);
myconnection.Open();
DateTime primaryKey= Convert.ToDateTime(dataGridView1.SelectedRows[0].Cells[0].Value);
SqlCommand AddNumberCommand = myconnection.CreateCommand();
AddNumberCommand.CommandText = "UPDATE dbo.Vagter SET [ansatID] = @ansatID WHERE [Dato] = @dato";
AddNumberCommand.Parameters.Add("@ansatID", SqlDbType.Int).Value = textBox1.Text;
AddNumberCommand.Parameters.Add("@dato", SqlDbType.DateTime).Value = primaryKey;
AddNumberCommand.ExecuteNonQuery();
myconnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MessageBox.Show("Du har valgt vagten.");
}
}
But, string ID = System.Security.Principal.WindowsIdentity.GetCurrent().Name does not help in this case. ID is also declared as 'int' datatype.
Expected result is, that if a currently logged in user write an other user's ID in textBox1 and try to update data in DataGridView pressing button, then he get an error message like ''You have to use your ID'' or something like that.