gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:48:21 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com