I'm facing an issue when trying to verify if a cell of a wpf datagrid is null, I always get a null reference exception even when I try to verify if it's null, can anyone help me here?
code bellow
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"]);
}
}
You should check whether the as operator actually 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"]);
}
}
Or better yet iterate through the 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"]);
}
}
}