c# - 如何检查数据网格行是否为空?

标签 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"]);
            }
        }
    }

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

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

An Invalid cast Exception gets thrown: "Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.Data.DataRowView"

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

最佳答案

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

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"]);
}

关于c# - 如何检查数据网格行是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24736843/

相关文章:

wpf - dataGrid 上的 SharedSizeGroup

c# - 继承控件的样式类似于基本控件

c# - 如何排除 "Project not selected to build for this solution configuration"消息在 Visual Studio 2013 的输出窗口中显示

c# - 如何使用 System.Runtime.Serialization.Json 解析这个字符串?

c# - 如何从 ComboBox C# Winforms 获取 ValueMember 值?

c# - LINQ to Entities - 多个连接 - 'Select' 上的空引用异常

c# - 使用标记方法将 Item Sourcing 转换为 ComboBox

c# - Expander扩展按钮wpf的移动位置

wpf - 图像以适应 WPF 中的网格单元格大小

c# - WPF 中的 MVVM - 一些不确定性