C# BindingSource 获取当前行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11376053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BindingSource Get Current Row
提问by
I cannot get current row value. How can i do?
我无法获取当前行值。我能怎么做?
bindingSource1.DataSource = LData; (LData is Generic List)
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;
}
}
}
I cannot get current row with :
我无法获得当前行:
MessageBox.Show(currentRow["NAME"].ToString());
Getting Err: InvalidCastException, how can i do? Thanks.
出现错误:InvalidCastException,我该怎么办?谢谢。
采纳答案by Damir Arh
You can't expect to have DataRowobjects in bindingSource1.Currentif you're setting DataSourceto a List<T>instead of to a DataTable. In your case bindingSource1.Currentwill contain an instance of the generic type.
如果您设置为 a而不是a DataRow,bindingSource1.Current则不能期望有对象。在您的情况下将包含泛型类型的实例。DataSourceList<T>DataTablebindingSource1.Current
I suppose you're initializing LData like this:
我想你是这样初始化 LData 的:
LData = new List<T>();
The property should then look like this:
该属性应如下所示:
public T currentRow
{
get
{
int position = this.BindingContext[bindingSource1].Position;
if (position > -1)
{
return (T)bindingSource1.Current;
}
else
{
return null;
}
}
}
And you could read the value like this (assuming Nameis a property of T):
您可以像这样读取值(假设Name是 的属性T):
MessageBox.Show(currentRow.Name);
Not tested of course, but something like this should work. Use the debugger in the following line to see what the contents of the Currentproperty are actually like:
当然没有经过测试,但这样的事情应该可以工作。使用以下行中的调试器查看Current属性的内容实际是什么样的:
return (T)bindingSource1.Current;

