2016-07-08 83 views
0

我正在使用C#处理Windows窗体应用程序。将过滤的DataGridView分配给DataRow []给出空值(过滤器有结果)

我的表格有DataGridView您可以添加/删除条目,条目有可编辑的Qty列,然后是Save按钮。

一旦点击Save,我要筛选的DataGridView条目0.00 Qty,然后通知用户有/是0.00 Qty名单上,否则将进行保存。 (见表格的截图点击保存之前)

Form where the user add/delete entry and set the Qty

我有这样下面的代码的形式:

private void SaveBtn_Click(object sender, EventArgs e) 
    { 
     if (isWithZeroQty() == true) 
     { 
      MessageBox.Show("Please check Quantity","System Alert",MessageBoxButtons.OK,MessageBoxIcon.Warning); 
     } 
     else 
     { 
      // Will do the saving.. 
     } 
    } 

    private bool isWithZeroQty() 
    { 
     DataRow[] result = (enrollmedsDataGridView.DataSource as DataTable).Select("Qty = 0.00 OR Qty = 0"); 

     if (result.Count() > 0) 
     { return true; } 
     else 
     { return false; } 
    } 

我的问题是NullReferenceException发生在这一行:

DataRow[] result = (enrollmedsDataGridView.DataSource as DataTable).Select("Qty = 0.00 OR Qty = 0"); 

经过我的进一步调查,将DataGridView强制转换为DataTable (enrollmedsDataGridView.DataSource as DataTable)时发生NullReferenceException。

是因为DataGridView是DataBounded到BindingSource?

如果是这样,我该如何解决这个问题。

在此先感谢您的帮助。

回答

0

我仍然无法找到NullReferenceException在上面的代码中出现的原因。

但作为一种解决方法,而不是过滤和铸造DataGridViewDataTable我用在每一行的foreach检查电池Qty如果有0 or 0.00值这在我结束工作正常。

请参见下面的代码:

private bool isWithZeroQty() 
    { 
     int zeros = 0; 
     foreach (DataGridViewRow row in enrollmedsDataGridView.Rows) 
     { 
      if ((row.Cells["Qty"].Value.ToString() == "0") || (row.Cells["Qty"].Value.ToString() == "0.00")) 
      { 
       zeros = 1; 
      } 
     } 
     if (zeros > 0) 
     { return true; } 
     else 
     { return false; } 
    }