An error message:
System.InvalidCastException' occurred in mscorlib.dll.Object cannot be cast from DBNull to other types.
is quite clear. It means that one of
startno
and
noofcheques
field is null!
You can check if the value is not null by using
IsDbNull[
^] method or you can replace
null
with default value:
int startno = 0;
int noofcheques = 0;
if(!Convert.IsDbNull(dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value))
startno = dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value;
if(!Convert.IsDbNull(dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value))
noofcheques = dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value;
int startno = Convert.IsDbNull(dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value)==true ? dgvwChqs.Rows[e.RowIndex].Cells["startno"].Value : 0;
int noofcheques = Convert.IsDbNull(dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value)==true ? dgvwChqs.Rows[e.RowIndex].Cells["noofcheques"].Value : 0;
dgvwChqs.Rows[e.RowIndex].Cells["endingno"].Value = startno + noofcheques;
Another way is to use nullable datatypes. For further details, please see:
Using Nullable Types (C# Programming Guide) | Microsoft Docs[
^]