奇数/偶数datagridview行背景颜色

Mar*_*rek 10 .net c# datagridview winforms

我有datagridview,现在我想根据行号是偶数还是奇数来改变每行的背景颜色.

我认为必须有更简单的方法来实现这一目标.然后使用例如这部分代码并对其进行修改,以便更改dtg行的颜色.如果这段代码是这样做的方法之一,有人可以帮助我改进它,这样如果狂热,索引出来就不会抛出异常吗?

public void bg_dtg()
    {
        try
        {

            for (int i = 0; i <= dataGridView1.Rows.Count ; i++)
            {
                if (IsOdd(i))
                {

                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(""+ex);
        }
    }

   public static bool IsOdd(int value)
   {
       return value % 2 != 0;
   }
Run Code Online (Sandbox Code Playgroud)

谢谢你的时间和答案.

Col*_*eel 21

DataGridView表单设计器中有一个备用行视图样式选项.AlternatingRowsDefaultCellStyle在属性网格中


Adi*_*dil 6

您正在访问异常,因为您正在访问不存在的行。GridView 行是从零开始的index,这意味着如果网格中有 10 行,则索引将从 0 到 9,您应该比行少迭代 1 行count。该i <= dataGridView1.Rows.Count会就最后一次迭代例外,因为当计数为10(总排十)和dataGridView1.Rows [10]不存在,因此抛出异常。

循环条件中的 <=更改为 <

for (int i = 0; i <= dataGridView1.Rows.Count ; i++)
Run Code Online (Sandbox Code Playgroud)

for (int i = 0; i < dataGridView1.Rows.Count ; i++)
Run Code Online (Sandbox Code Playgroud)

您应该AlternatingRowsDefaultCellStyle属性来设置替代行样式以保持简单和高效。


小智 5

你可以尝试这个代码

 for (int i = 0; i < GridView1.Rows.Count; i++) {

     if (i % 2 == 0) {
       GridView1.Rows[i].Cells[0].Style.BackColor = System.Drawing.Color.Green;
       GridView1.Rows[i].Cells[1].Style.BackColor = System.Drawing.Color.Green;
     }
     else {
       GridView1.Rows[i].Cells[0].Style.BackColor = System.Drawing.Color.Red;
       GridView1.Rows[i].Cells[1].Style.BackColor = System.Drawing.Color.Red;
     }
}
Run Code Online (Sandbox Code Playgroud)