c# - BindingSource 获取当前行

标签 c# datasource generic-list bindingsource

我无法获取当前行值。我该怎么办?

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 中的对象如果你设置 DataSourceList<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;
        }
    }
}

您可以像这样读取值(假设 NameT 的属性):

MessageBox.Show(currentRow.Name);

当然没有测试过,但像这样的东西应该可以工作。使用以下行中的调试器查看 Current 的内容属性实际上是这样的:

return (T)bindingSource1.Current;

关于c# - BindingSource 获取当前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11376053/

相关文章:

c# - 如何将对象列表转换或转换为对象队列

.net - 如何将 XMLSerializer 与包含 IList<T> 成员的 CaSTLe ActiveRecord 结合使用

c# - 在 Visual Studio 中按 NUnit 的类别属性运行/分组测试

c# - C# MSVS 中的资源

c# - 绑定(bind)列表到数据源

java - 从 XML 文件配置 JNDI InitialContext

c# - 使用 .NET 自定义序列化时测试可选字段

c# - 如何反序列化具有动态属性名称的 JSON 对象?

java - Tomcat6 MySql JDBC 数据源配置

c# - 为什么 List<> 实现 IList