Search code examples
c#datasourcegeneric-listbindingsource

BindingSource Get Current Row


I cannot get current row value. How can i do?

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.


Solution

  • You can't expect to have DataRow objects in bindingSource1.Current if you're setting DataSource to a List<T> instead of to a DataTable. In your case bindingSource1.Current will contain an instance of the generic type.

    I suppose you're initializing LData like this:

    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 Name is a property of 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 Current property are actually like:

    return (T)bindingSource1.Current;