0

I typically use this code to retrieve data when the grid control data source is bonded to the data table

        private void AddSelectedRowsToList()
        {
            var selectedRows = gridView1.GetSelectedRows();
            for (var i = 0; i < selectedRows.Length; i++)
            {
                var row = (gridView1.GetRow(selectedRows[i]) as DataRowView).Row;

                string firstName = row["FirstName"].ToString();
                string lastName = row["LastName"].ToString();

                usersInfo.Add(new SAPSUserInfo(firstName, lastName));
            }
        }

As soon as I bonded grid control data source to BindingSource, I got this error

System.NullReferenceException HResult=0x80004003
Message=Object reference not set to an instance of an object.

On this line

var row = (gridView1.GetRow(selectedRows[i]) as DataRowView).Row;

How do I get selected rows when grid control is bound to BindingSource?
Update
This the type of my BindingSource

private readonly BindingSource listEmployeeDto = new();
M.Bouabdallah
  • 530
  • 10
  • 29
  • A preciese answer depend on which data source is behind BindingSource in your case. Is it DataTable? The obvious cause of the issue, is that the GetRow method did not return a DataRowView instance. So you can use a debugger to find out which type it has – Nikita K Jun 09 '22 at 08:34
  • The binding source is IEnumerable and the GetRow method return EmployeeDto – M.Bouabdallah Jun 09 '22 at 08:54

1 Answers1

0

thanks to Nikita K this is how I solved it

private void AddSelectedRowsToList()
{
    var selectedRows = gridView1.GetSelectedRows();
    for (var i = 0; i < selectedRows.Length; i++)
    {
        var employeeDto = gridView1.GetRow(selectedRows[i]) as EmployeeDto;
        
        usersInfo.Add(new SAPSUserInfo(employeeDto.FirstName,employeeDto.LastName));
    }

}
M.Bouabdallah
  • 530
  • 10
  • 29