Error with DB NULL in datagridview

0

I'm trying to pass a column from one datagridview to another and I need to add more days, but at the time of making the conversion and showing it on the other table I get the following error.

System.InvalidCastException' en mscorlib.dll

Información adicional: Object cannot be cast from DBNull to other types.

My code is as follows:

  DateTime?  ini;
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {




                    dataGridView7.Rows.Add(DBNull.Value);
                    dataGridView7.Rows.Add(ds.Tables[0].Rows[i]["Required Date"]);
                    ini = Convert.ToDateTime(ds.Tables[0].Rows[i]["Required Date"] );
                    ini = ini.Value.AddDays(75);
                    //MessageBox.Show( String.Format("{0:dd/MM/yyyy}",ini));
                    dataGridView7.Rows.Add(String.Format("{0:dd/MM/yyyy}", ini));
                }

The error marks me on the next line

   ini = Convert.ToDateTime(ds.Tables[0].Rows[i]["Required Date"] );

I do not know how you can enter the same null that you have in the original datagridview. Thanks

    
asked by oscar ramirez 11.04.2017 в 17:39
source

1 answer

1

One option is to check if the data in the DataRow is null before assigning it to ini, something like this:

ini = (ds.Tables[0].Rows[i]["Required Date"] != DBNull.Value ? 
           (DateTime?)Convert.ToDateTime((ds.Tables[0].Rows[i]["Required Date"].ToString()) 
          : null;

This in case that RequiredDate is of type string, if it is DateTime you can simply do this:

ini = ds.Tables[0].Rows[i]["Required Date"] != DBNull.Value ?
         (DateTime?)ds.Tables[0].Rows[i]["Required Date"] 
         : null;

Although probably your problem is simply that you lack the% a% cast, so this should work too:

ini = (DateTime?)ds.Tables[0].Rows[i]["Required Date"];

Edit It seems that letters appear in that column in some rows. You will then have to check if it is possible to convert it to DateTime? :

DateTime tempDate;
if (DateTime.TryParse(ds.Tables[0].Rows[i]["Required Date"].ToString(), out tempDate))
{
    ini = tempDate;
}
else
{
    ini=null;
}
    
answered by 11.04.2017 / 17:55
source