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