1

I have the following code:

// row is a DatGridViewRow object
IEnumerator<DataGridCell> cells = row.Cells.GetEnumerator();

I get compile errors specifying that I

cannot implicitly convert type System.Collections.IEnumerator to System.Collections.Generic.IEnumerator

and that I need to do an explicit cast. When I try doing that via.

IEnumerator<DataGridCell> cells = (IEnumerator<DataGridCell>)row.Cells.GetEnumerator();

I get a run-time error.

Any ideas?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Lawrence Vo
  • 177
  • 2
  • 11

3 Answers3

6

This row.Cells.GetEnumerator() returns an IEnumerator but you are trying to assign it to an IEnumerator<DataGridViewCell> which can't be done and you get an exception. Adding (IEnumerator<DataGridCell>) in front of it won't help because still it is a different type.

To achieve that use .Cast before:

IEnumerator<DataGridCell> cells = row.Cells.Cast<DataGridViewCell>().GetEnumerator();

IMO a better option is to use IEnumerable<DataGridCell>:

IEnumerable<DataGridCell> cells = row.Cells.Cast<DataGridViewCell>();
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
2

Try using the cast operator first.

IEnumerator<DataGridCell> cells = row.Cells.Cast<DataGridCell>().GetEnumerator();
Cheick
  • 2,154
  • 24
  • 28
1
IEnumerator<DataGridCell> cells = row.Cells.Cast<DataGridCell>().GetEnumerator();

For those following along at home:

var able = (IEnumerable)new List<String>();

IEnumerator<String> tor = able.Cast<String>().GetEnumerator();

Beats me why OP wants IEnumerator rather than IEnumerable (in fact I suspect he might be better off with the latter), but that's the question he asked.