【问题标题】:How to check if datagrid row is empty?如何检查datagrid行是否为空?
【发布时间】:2014-07-14 22:22:39
【问题描述】:

我有一个由 MySQL 表填充的数据网格。这里的问题是我添加了一个 SelectionChanged 事件。

private void RegistrationDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        // if the datagrid has an index value of 0 and above
        if (RegistrationDataGrid.SelectedIndex >= 0)
        {
            // Exception gets thrown here
            DataRowView row = (DataRowView)RegistrationDataGrid.SelectedItems[0];

            // if the column Tag of the selected row in the datagrid is not empty
            if (row["Tag"] != null)
            {
                //put the content of the cell into a textbox called tag
                tag.Text = Convert.ToString(row["Tag"]);
            }
        }
    }

上面的代码旨在捕获所选行的特定列中单元格的值。这很好用。

如果您选择最后一行,即始终存在的那一行,就会出现问题。底部是空的,里面什么都没有。

抛出一个无效的转换异常:“无法转换类型的对象 'MS.Internal.NamedObject' 输入 'System.Data.DataRowView"

我的假设是这与所选行为空的事实有关。 我只需要找到一种方法让事件在被选中时忽略该行。有什么线索吗?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    如果您不确定它是否会真正成功执行,请避免显式转换。我会用这个:

    var row = RegistrationDataGrid.SelectedItems[0];
    DataRowView castedRow = RegistrationDataGrid.SelectedItems[0] as DataRowView;
    
    if (castedRow != null && castedRow ["Tag"] != null) <------ DONT skip on checking castedRow for null, jumping directly to indexed access.
    {
         //put the content of the cell into a textbox called tag
         tag.Text = Convert.ToString(castedRow["Tag"]);
    }
    

    【讨论】:

    • 天才!非常感激。建议注意。
    • 不客气。您也可以使用带有“is”的检查,但这将是多余的,因为无论如何您都将使用转换后的结果。使用“as”更方便,开销更少
    【解决方案2】:

    在使用该单元格之前,您应该使用String.IsNullOrEmpty() 函数来验证该单元格的内容。此外,在此之前添加另一个验证以确保 row!=nullcastedRow!=null

    关于您对“最后一行空”的描述 - 这可能是一个“添加新行”模板:检查 DataGridView.AllowUserToAddRows 属性(如果您不使用它,请将其设置为 false,以便最后一个“空行” " 会消失)。

    带有异常处理的最终代码可能如下所示:

    private void RegistrationDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DataRowView _drv;
        try 
        {
            _drv = RegistrationDataGrid.SelectedItems[0] as DataRowView;
            if (_drv != null && _drv ["Tag"] != null && !String.IsNullOrEmpty(Convert.ToString(_drv ["Tag"]) ) 
            {
                tag.Text = Convert.ToString(_drv["Tag"]);
            }
            else{tag.Text=String.Empty;}
        }
        catch{tag.Text=String.Empty;}
        finally{_drv=null;}
    

    }

    希望这会有所帮助。问候,

    【讨论】:

    • 我明白你的意思。问题是在“row”声明中抛出异常......“row!=null”必须放在后面。
    • 它是否适用于任何具有常规数据的行(根据您的情况,不是空行)?
    • 是的。只要它有数据,它几乎适用于我扔给它的任何行
    猜你喜欢
    • 1970-01-01
    • 2021-08-16
    • 2011-12-15
    • 1970-01-01
    • 2017-11-15
    • 2020-05-29
    • 2018-04-02
    • 2016-04-05
    • 2018-01-08
    相关资源
    最近更新 更多