【问题标题】:how can i change a backcolor of odd and even rows in datagrid view?如何更改 datagridview 中奇数行和偶数行的背景色?
【发布时间】:2010-12-11 17:30:05
【问题描述】:

我在数据网格视图中有 10 行... 我用 V S 2010 我怎样才能改变奇数行和偶数行不同的背景色..?? 我尽力而为,但我有一个错误是: 索引超出范围。必须是非负数且小于集合的大小。参数名称:索引

如何在设置所有行背景色后制作单列背景色

我在表单加载事件上编写我的代码.. 我的代码是vb.net(windows形式)如下:

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

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    如果我没记错的话,我认为只是你需要换行:

    While CountR <= DataGridView1.RowCount
    

    While CountR < DataGridView1.RowCount
    

    换句话说,最高索引比行数小一。

    或者也许你可以用这样的东西替换你所有的代码(可能是一些错误,在没有 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 
    

    应该怎么做:为每一行更改颜色,并在使用一种颜色后切换到另一种颜色,等等,直到所有行都被着色。

    【讨论】:

      【解决方案2】:

      我对 vb.net 和 VS 2008 还是很陌生,但前几天我阅读了有关 datagridview 的信息,并在 MSDN 中找到了这个 article。 datagridview 有一个名为 AlternatingRowsDefaultCellStyle 的属性,它覆盖奇数(或偶数)行的背景颜色。它是这样设置的:

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

      我希望这是您正在寻找的(如果不是,我很抱歉......)。

      【讨论】:

        【解决方案3】:

        for / while 是错误的方式!如果您有很多记录,那么您的代码可能会很慢。

        我认为这是正确的方法:

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

        【讨论】:

          【解决方案4】:

          试试这个:

          <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>
          

          这将使赔率成为您的一种颜色,而偶数保持白色。

          【讨论】:

          • For each row in datagridviewrow in datagridview1.rows 应该是 For Each row In datagridview1.rows。这是一个很好的解决方案。
          【解决方案5】:

          您可以通过以下操作无需代码即可完成此操作; 1.点击DataGridView 2. 在属性面板的外观下,单击 AlternatingRowDefaultCellStyle 3. 将出现一个窗口,您可以在其中对 DataGrid 进行多项更改 (你要改变的是'BackColor')

          【讨论】:

            猜你喜欢
            • 2013-08-21
            • 2021-12-31
            • 1970-01-01
            • 2011-06-17
            • 1970-01-01
            • 1970-01-01
            • 2013-01-09
            • 1970-01-01
            • 2011-03-11
            相关资源
            最近更新 更多