J
JonOfAllTrades
Good afternoon (for everyone in time zones -10 through +1, at the moment).
This is a minor problem, but it's bugging me, it seems like there should be a
graceful solution.
I need to iterate over either the selected rows in a DataGridView, or (if
none are selected) ALL the rows. Either way I perform the same operations.
At the moment, I have a switch leading to one of two foreach loops, each with
identical content. What I'd like to do is choose one of two collections
(.Rows or .SelectedRows) and then iterate over it - no repeated code.
However, the types of these parameters are DataGridViewRowCollection and
DataGridViewSelectedRowCollection rather than IEnumerable<DataGridViewRow>.
The docs say that they implement this interface, or rather implement
IEnumerable, but it's invalid to cast up. This is what I'd like to get
working:
IEnumerable<DataGridViewRow> rows =
DataContacts.SelectedRows.Count == 0 ?
DataContacts.Rows : DataContacts.SelectedRows;
foreach (DataGridViewRow row in rows)
/*Do stuff with the row*/
This fails at compile time; casting .Rows and .SelectedRows to
IEnumerable<DataGridViewRow> fails at runtime. This is my inelegant
workaround:
if (DataContacts.SelectedRows.Count == 0)
{
foreach (DataGridViewRow row in DataContacts.Rows)
/*Do stuff with the row*/ }
else
{
foreach (DataGridViewRow row in DataContacts.SelectedRows)
/*Do stuff with the row*/ }
Any thoughts? I suppose could wrap the "Do stuff" part in a function, or
use a delgate, but it seems clumsy. Thanks!
This is a minor problem, but it's bugging me, it seems like there should be a
graceful solution.
I need to iterate over either the selected rows in a DataGridView, or (if
none are selected) ALL the rows. Either way I perform the same operations.
At the moment, I have a switch leading to one of two foreach loops, each with
identical content. What I'd like to do is choose one of two collections
(.Rows or .SelectedRows) and then iterate over it - no repeated code.
However, the types of these parameters are DataGridViewRowCollection and
DataGridViewSelectedRowCollection rather than IEnumerable<DataGridViewRow>.
The docs say that they implement this interface, or rather implement
IEnumerable, but it's invalid to cast up. This is what I'd like to get
working:
IEnumerable<DataGridViewRow> rows =
DataContacts.SelectedRows.Count == 0 ?
DataContacts.Rows : DataContacts.SelectedRows;
foreach (DataGridViewRow row in rows)
/*Do stuff with the row*/
This fails at compile time; casting .Rows and .SelectedRows to
IEnumerable<DataGridViewRow> fails at runtime. This is my inelegant
workaround:
if (DataContacts.SelectedRows.Count == 0)
{
foreach (DataGridViewRow row in DataContacts.Rows)
/*Do stuff with the row*/ }
else
{
foreach (DataGridViewRow row in DataContacts.SelectedRows)
/*Do stuff with the row*/ }
Any thoughts? I suppose could wrap the "Do stuff" part in a function, or
use a delgate, but it seems clumsy. Thanks!