如何检查datagrid行是否为空?

时间:2014-07-14 12:47:26

标签: c# wpf

我有一个由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"

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

2 个答案:

答案 0 :(得分: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;}

}

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

答案 1 :(得分:2)

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

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"]);
}
相关问题