检查datarowview是否为null?

时间:2018-11-02 21:53:28

标签: c# wpf datagrid datarowview

尝试验证wpf datagrid的单元格是否为空时遇到问题,即使尝试验证是否为空,我也始终会得到空引用异常,有人可以在这里帮助我吗?

下面的代码

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"]);
            }

        }

1 个答案:

答案 0 :(得分:1)

您应检查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"]);
        }
    }
}