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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments