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.
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;
}
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>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With