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());

Getting Err:InvalidCastException,我该怎么办?谢谢

如果将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;
        }
    }
}

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

MessageBox.Show(currentRow.Name);

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

return (T)bindingSource1.Current;

最新更新