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, doesn't work, as I get an error:
System.InvalidCastException: An object of type 'System.DBNull' cannot be converted to the 'System.String' type
I have tried it with this code:
if ((string)dataGridView1.SelectedCells[0].OwningRow.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.AddWithValue("@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("The cell has already a value.");
}
The expected result is that when a user select in DataGridView
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." Moreover, the column ansatID is of data type "int". This is also shown on following picture:
(string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value == null
DBNull cannot be converted to any datatype directly so you would need to check if it is DBNull before doing the conversion
something like
if (dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value == DBNull.Value)
//dosomething
else
//do something else
Or depending on how you read it from the database you can use the extension method to save yourself some typing
dataRow.Field<string>("Column Name")