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?

2

3 Answers 3

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>();
6
  • Downvoter please explain Oct 11, 2016 at 19:39
  • I didn't downvote you, but OP said he wants IEnumerator, not IEnumerable. It's fair to ask him if he's sure that's really what's right for him, but you can't just say "here's something else, good luck". Oct 11, 2016 at 19:43
  • 1
    @EdPlunkett - Ya :) just saw my mistake and corrected :) Oct 11, 2016 at 19:43
  • @Lawrence Vo - Did this help you solve your problem? Oct 11, 2016 at 21:25
  • @GiladGreen yes it did, thanks! Oct 12, 2016 at 14:47
2

Try using the cast operator first.

IEnumerator<DataGridCell> cells = row.Cells.Cast<DataGridCell>().GetEnumerator();
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.

2

Not the answer you're looking for? Browse other questions tagged or ask your own question.