Click here to Skip to main content
13,091,268 members (51,350 online)
Rate this:
Please Sign up or sign in to vote.
See more:

Please see below:

int i = 0;
           foreach (DataGridViewRow dgr in this.dataGridView1.Rows)
               dgr.DefaultCellStyle.BackColor = ((i % 2) == 0) ? Color.LightGray : Color.DarkGray;

Can anybody tell me how the above code can be converted into LINQ please?

Many thanks in advance
Posted 7-Feb-13 3:59am
joshrduncan2012 7-Feb-13 10:25am
What have you tried so far?
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Best solution I can come up with is

Buy ReSharper, and there is a function to convert foreach into LINQ.

That's what I have used in the past, and miss it now :([^]
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

First, why do this in LINQ? The code you have does the job without it, so I'd suggest taking a look at why it is necessary to change.

If you want to you could clean you line a little:
bool isOddRow = true;
foreach (DataGridViewRow dgr in this.dataGridView1.Rows)
    dgr.DefaultCellStyle.BackColor = isOddRow ? Color.LightGray : Color.DarkGray;
    isOddRow = !isOddRow;

One positive change you could make is to take advantage of AlternatingRowsDefaultCellStyle and RowsDefaultCellStyle, which would probably make the above redundant totally, see MSDN for examples.
Member1978 7-Feb-13 14:50pm
Thanks Keith
You are Geordie then. I went to Newcastle Polytechnic many years ago. I agree with you people up in Newcastle are very kind indeed. I had such a good time there.
Cheers for the solution.
Keith Barrow 7-Feb-13 15:04pm
I am indeed, born & bred. I almost went to Northumbria Uni (hasn't been a Poly since my undergrad days in the mid 90s) to read my MSc, but the course at Newcastle suited my needs better as it had less emphasis on DB work. Glad to be of help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.170813.1 | Last Updated 7 Feb 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100