开发者

how can i change a backcolor of odd and even rows in datagrid view?

i have 10 rows in datagrid view ... i use V S 2010 How can i change a backcolor of odd and even rows different..?? i try my best but i has one error that is : Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

开发者_如何学运维

how can i make a single column backcolor after all rows backcolor is set

i write my code on form load event.. my code is in vb.net(windows form) is as follows:

Dim CountR As Integer
   CountR = 0
   While CountR <= DataGridView1.RowCount

       If CountR Mod 2 = 0 Then
                          DataGridView2.Rows(CountR).DefaultCellStyle.BackColor = Color.Pink
       Else
       DataGridView2.Rows(CountR).DefaultCellStyle.BackColor = Color.SkyBlue    

       End If
       CountR = CountR + 1
   End While


If I'm not mistaken I think it's just that you need to change the line:

While CountR <= DataGridView1.RowCount

to

While CountR < DataGridView1.RowCount

In other words, the highest index is one less than the rowcount.

Or maybe you could just replace all your code with something like this (probably some mistake in this, typed from memory without IDE):

Dim c as Color = Color.Pink
For Each row As DataGridViewRow In DataGridView1.Rows
    row.DefaultCellStyle.BackColor = c
    c = If(c = Color.Pink, Color.SkyBlue, Color.Pink)
End 

Which should do: For each row change the colour, and after using a colour, switch to the other one etc until all rows have been coloured.


I'm quite new to vb.net and VS 2008, but the other day I read about datagridview and found this article in MSDN. There is a property of datagridview called AlternatingRowsDefaultCellStyle that overrides the background color of rows for odd (or even) rows. It is set this way:

dataGridView1.RowsDefaultCellStyle.BackColor = Color.LightGray
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray

I hope it's what you're looking for (and my apologies if not...).


The for / while is a wrong way! If you have a lot records than your code can be slow.

I think this is the right way:

Dim cs As New System.Windows.Forms.DataGridViewCellStyle
cs.BackColor = Color.Aqua
Me.DataGridView1.AlternatingRowsDefaultCellStyle = cs


Try this:

<code>
  For each row in datagridviewrow in datagridview1.rows
  If not row.index / 2 = int(row.index / 2) then row.defaultcellstyle.backcolor = color.{your color choice}
  Next
</code>

This will make odds your one color while evens stay white.


You can do this without code by doing the following; 1. Click the DataGridView 2. In the Properties Panel, under Appearance, click AlternatingRowDefaultCellStyle eclipses 3. A window will appear where you can make multiple changes to the DataGrid (the one you want to change is 'BackColor')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜