I have the following code:
This is declared the variable at the beginning of all my code:
int editado = 0;
This method I use in a button.
public void Insertar
{ try
{
for (int i = 0; i < dgvFormulacion.Rows.Count - 1; i++)
{
Program.con.Close();
Program.con.Open();
cm = new SqlCommand("insert into Formulacion values(@NombreConcepto,@cantidad,@precio,@editado", Program.con);
cm.Parameters.AddWithValue("@NombreConcepto", dgvFormulacion.Rows[i].Cells["MateriaPrima"].Value);
if (dgvFormulacion.Rows[i].Cells["PrecioUnitario"].Value == null)
{
dgvFormulacion.Rows[i].Cells["PrecioUnitario"].Value = "0";
}
if (dgvFormulacion.Rows[i].Cells["Cant"].Value == null)
{
dgvFormulacion.Rows[i].Cells["Cant"].Value = "0";
}
if (Convert.ToBoolean(dgvFormulacion.Rows[i].Cells["Editar"].Value) == true)//////Linea de error DBnull
{
editado = 1;
}
else if (Convert.ToBoolean(dgvFormulacion.Rows[i].Cells["Editar"].Value) == false)
{
editado = 0;
}
cm.Parameters.AddWithValue("@editado", editado);
cm.Parameters.AddWithValue("@precio", dgvFormulacion.Rows[i].Cells["PrecioUnitario"].Value);
cm.Parameters.AddWithValue("@cantidad", dgvFormulacion.Rows[i].Cells["Cant"].Value);
cm.ExecuteNonQuery();
cm.Dispose();
Program.con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When I try to register that field in the database it shows me the error
Error converting DBNull
This error sometimes appears to me and sometimes it does not ... How can I correct it. This is the exception:
Excepción producida: "System.InvalidCastException" en mscorlib.dll ("No se puede convertir un objeto DBNull en otros tipos.") System.InvalidCastException