我无法获取当前行值。我该怎么办?
bindingSource1.DataSource = LData; (LData is Generic List)
public DataRow currentRow
{
get
{
int position = this.BindingContext[bindingSource1].Position;
if (position > -1)
{
return ((DataRowView)bindingSource1.Current).Row;
}
else
{
return null;
}
}
}
我无法通过 :
获取当前行 MessageBox.Show(currentRow["NAME"].ToString());
出现错误:InvalidCastException,我该怎么办? 谢谢。
最佳答案
你不能指望拥有 DataRow
bindingSource1.Current
中的对象如果你设置 DataSource
到 List<T>
而不是 DataTable
.在你的情况下 bindingSource1.Current
将包含通用类型的实例。
我想你是这样初始化 LData 的:
LData = new List<T>();
属性应该如下所示:
public T currentRow
{
get
{
int position = this.BindingContext[bindingSource1].Position;
if (position > -1)
{
return (T)bindingSource1.Current;
}
else
{
return null;
}
}
}
您可以像这样读取值(假设 Name
是 T
的属性):
MessageBox.Show(currentRow.Name);
当然没有测试过,但像这样的东西应该可以工作。使用以下行中的调试器查看 Current
的内容属性实际上是这样的:
return (T)bindingSource1.Current;
关于c# - BindingSource 获取当前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11376053/