当我试图验证wpf数据网格的单元格是否为null时,我遇到了一个问题,即使我试图验证它是否为null,我也总是得到一个null引用异常,有人能帮我吗?
下方的代码
for (int i = 0; i < commandeDataGrid.Items.Count; i++)
{
DataRowView row = commandeDataGrid.Items[i] as DataRowView;
if (row["Prix Total TTC"]!=null)
{
count = count + Convert.ToInt16(row["Prix Total TTC"]);
}
}
您应该检查as运算符是否实际返回DataRowView
:
for (int i = 0; i < commandeDataGrid.Items.Count; i++)
{
DataRowView row = commandeDataGrid.Items[i] as DataRowView;
if (row != null && row["Prix Total TTC"] != null)
{
count = count + Convert.ToInt16(row["Prix Total TTC"]);
}
}
或者更好地通过ItemsSource
:进行迭代
DataView dataView = commandeDataGrid.ItemsSource as DataView;
if (dataView != null)
{
foreach (DataRowView row in dataView)
{
if (row["Prix Total TTC"] != null)
{
count = count + Convert.ToInt16(row["Prix Total TTC"]);
}
}
}