Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagridview how to cast selected row to custom object

I use c# winforms with MSSQL database. I have table in database "Pilots" , i fill datagridview "dgvPilots", with data from Pilots table.

dgvPilots.DataSource = Connection.dm.Pilots.ToList();

I enable multiselect. now i need to get multiselected data from datagridview. How can i multiselected rows cast to "Pilots" object and get PilotsID.

My current error is "Unable to cast object type DataGridViewRow to type ".Data.Pilots"...

i also try casting like this

dgvPilots.SelectedRows.Cast<Pilots>().ToList();

but it return DataGridViewRow item type.

like image 257
Srđan Marković Avatar asked May 07 '14 14:05

Srđan Marković


4 Answers

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

like image 83
Peter Avatar answered Oct 07 '22 14:10

Peter


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.

like image 44
Tarec Avatar answered Oct 07 '22 14:10

Tarec


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

            foreach (i in indexes)
            {
                Pilots Pilot = (Pilots)DataGrid1.Rows[i].DataBoundItem;
            }
like image 34
Stas Avatar answered Oct 07 '22 13:10

Stas


This simple generic extension method is what I've always used:

    public static List<T> ToList<T>(this DataGridViewSelectedRowCollection rows)
    {
        var list = new List<T>();
        for (int i = 0; i < rows.Count; i++)
            list.Add((T)rows[i].DataBoundItem);
        return list;
    }

Use: dgvPilots.SelectedRows.ToList<Pilots>()

like image 24
WeskerTyrant Avatar answered Oct 07 '22 14:10

WeskerTyrant