Friday, 17 May 2019

winforms - How to check if a cell in selected row in dataGridView is empty/null, using C#?

I'm trying to write a code, which checks if a cell in selected row in dataGridView is empty/null before the cell will be updated with a value. The code, which I wrote, works but no matter if there is a value in cell in selected row or not, the data are not updated. I have tried with this code:



 if (dataGridView1.SelectedRows[0].Cells[1].Value == null)
{
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 AddNumbeCommand = myconnection.CreateCommand();
AddNumbeCommand.CommandText = "UPDATE dbo.Vagter SET [ansatID] = @ansatID WHERE [Dato] = @dato";
AddNumbeCommand.Parameters.Add("@ansatID", SqlDbType.Int).Value = textBox1.Text;
AddNumbeCommand.Parameters.Add("@dato", SqlDbType.DateTime).Value = primaryKey;
AddNumbeCommand.ExecuteNonQuery();
myconnection.Close();

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MessageBox.Show("The cell is updated.");
}


}
else
{
MessageBox.Show("There is already a value in the cell.");
}


As I mentioned befor, the actual result is that no matter if there is a value in cell in selected row or not, the data are not updated. The expected result is that when a user select in dataGrdView a row where cell under column ansatID already has a value, write a value in textBox1, and press on ''Tilføj ansatID til vagten'', the he get error:"There is already a value in the cell.". If he will select a row where cell under column ansatID is empty, write a value in textBox1, and press on ''Tilføj ansatID til vagten'', then the SQL query will be executed and he gets message "The cell is updated." This is also shown on following picture: enter image description here

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...