Datagridview how to cast selected row to custom object

You will need to iterate the collection and go after the DataBoundItem property which is the underlying data.

var pilots = new List<Pilots>(grid.SelectedRows.Count);

for(int index = 0; index < grid.SelectedRows.Count; index++)
{
   var selectedRow = grid.SelectedRows[index];
   var pilot = (Pilots)selectedRow.DataBoundItem;

   pilots.Add(pilot);
}

The code above shows how you can achieve this, (I freehanded the code so forgive any syntax errors).

Here is the msdn article on the DataBoundItem property: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.databounditem(v=vs.110).aspx


I don't know what your DB structure is but

var selectedPilots = dgvPilots.SelectedRows.Cast<Pilots>().ToList();

is the proper way to do it. However I do suspect Pilots in your case is a DataTable, and what you need is to cast those items to proper Class type - If I'd have to shoot, I'd say you've got a Pilot (singular) class, that you should cast to.


List<int> indexes = DataGrid1.SelectedRows.Cast<DataGridViewRow>().Select(x => x.Index).ToList();

            foreach (i in indexes)
            {
                Pilots Pilot = (Pilots)DataGrid1.Rows[i].DataBoundItem;
            }