在c#datagridview

问题描述

我正在将Excel工作表导入datagridview后尝试为行和列着色。

@H_404_2@
  • 行(A1,A2,A3,A4,A5,A6)应以红色突出显示。 (最大行数为35)

  • 列(字段,记录1,记录2,记录3,记录4,记录5,记录6,记录7)应以橙色突出显示。 (列数不是固定的,每次都会不同)。

     dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Orange;
    dataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Red;
    
  • 但是上面的代码为不需要的区域着色。该如何解决

    (所附图片中的彩色区域应为白色,箭头所指区域应考虑着色。)

    enter image description here

    解决方法

    您可以尝试以下代码来设置第一行的颜色和第一列的颜色。

    dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Green;
    dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Red;
    

    结果: enter image description here

    ,

    您需要设置默认的行颜色和备用的行颜色样式。

    https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-set-alternating-row-styles-for-the-windows-forms-datagridview-control?view=netframeworkdesktop-4.8

    this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque;
    this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor =
        Color.Beige;