Reputation: 6061
Is there a direct way to do this, or do I need to iterate over the DataGridView.SelectedRows, and then access DataGridViewRow.DataBoundItem for each row to create one?
Upvotes: 1
Views: 618
Reputation: 4174
A generic extension method to add "SelectedDataRows" to DataGridViews:
public static T[] SelectedDataRows<T>(this DataGridView dg) where T : DataRow
{
T[] rows = new T[dg.SelectedRows.Count];
for (int i = 0; i < dg.SelectedRows.Count; i++)
rows[i] = (T)((DataRowView)dg.SelectedRows[i].DataBoundItem).Row;
return rows;
}
This is generic so that you can return a typed data row using Typed Datasets. You could make yours just return a DataRow[]
if you wanted. This also assumes that your DataGridView has a DataView
bound to it.
Upvotes: 0
Reputation: 273244
The DataGridView does not provide a SelectedDataRows and SelectedRows in not Linq-enabled, so Yes, you will have to write a foreach loop.
Upvotes: 3