【问题标题】:Assigning filtered DataGridView to DataRow[] giving null value (filter has result)将过滤后的 DataGridView 分配给 DataRow[] 给出空值(过滤器有结果)
【发布时间】:2016-11-10 15:31:12
【问题描述】:

我正在使用 C# 开发 Windows 窗体应用程序。

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

点击Save后,我想过滤0.00 QtyDataGridView条目,然后通知用户列表中有0.00 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 的?

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

提前感谢您的帮助。

【问题讨论】:

    标签: c# winforms datagridview nullreferenceexception


    【解决方案1】:

    我还是找不到上面代码出现 NullReferenceException 的原因。

    但作为一种解决方法,我不是将 DataGridView 过滤和转换为 DataTable,而是在每一行上使用 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; }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-12
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多