如何转换或跳过null
日期时间,我的日期时间来自数据库
我使用的代码是
private void gridView1_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
{
GridView view = sender as GridView;
for (int i = 0; i < gridView1.RowCount; i++)
{
if (gridView1.GetDataRow(i) == null)
{
break;
}
DateTime sg = Convert.ToDateTime(gridView1.GetDataRow(i)["date"]);
if (!repositoryItemComboBox1.Items.Contains(sg))
{
repositoryItemComboBox1.Items.Add(sg);
}
}
}
当我尝试运行程序时,因为在date的数据库中得到null类型,它给我错误:
对象无法从DBNULL转换为其他类型。在 system.dbnull.system.iconvertible.toDatetime(IformatProvider provider)
答案 0 :(得分:0)
使用DBNull.Value
:
DateTime? sg = null;
if(gridView1.GetDataRow(i)["date"] != DBNull.Value)
sg = Convert.ToDateTime(gridView1.GetDataRow(i)["date"]);
if (sg != null && !repositoryItemComboBox1.Items.Contains(sg))
{
repositoryItemComboBox1.Items.Add(sg);
}
答案 1 :(得分:0)
您可以在此之前检查gridView1.GetDataRow(i)["date"]
是否DBNull
;
DateTime sg;
if(!(gridView1.GetDataRow(i)["date"] is DBNull))
{
sg = Convert.ToDateTime(gridView1.GetDataRow(i)["date"]);
}