How do I get selected rows when grid control is bound to BindingSource?

374 Views Asked by At

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

There are 1 best solutions below

0
M.Bouabdallah On

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

}