检查数据行视图是否为空?

Checking if a datarowview is null?

我在尝试验证 wpf 数据网格的单元格是否为 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 运算符是否实际上 returns a 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"]);
        }
    }
}