【问题标题】:BindingSource Get Current RowBindingSource 获取当前行
【发布时间】:2012-07-07 15:01:09
【问题描述】:

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

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,我该怎么办? 谢谢。

【问题讨论】:

    标签: c# datasource generic-list bindingsource


    【解决方案1】:

    如果您将DataSource 设置为List<T> 而不是DataTable,则不能指望在bindingSource1.Current 中有DataRow 对象。在您的情况下,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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 2011-08-10
      • 2013-07-07
      • 2013-02-06
      • 1970-01-01
      • 2012-09-06
      • 2019-08-18
      相关资源
      最近更新 更多