设置WinForm, dataGridView某行或某列背景或字体颜色和隔行换色

首次发布:2023-10-31 16:07

下面效果图是设置某行背景颜色和某Cells字体颜色

demo.png

下面是核心代码

 public partial class Form1 : Form
 {
     public Form1()
     {
         InitializeComponent();
     }

     private void Form1_Load(object sender, EventArgs e)
     {
         this.dataGridView1.DataSource = Source();
         //隔行换色
         //this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Red;
         //this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Green;

         //第3行背景颜色设置为红色
         this.dataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.Red;
         //第5行第三列 字体为红色
         this.dataGridView1.Rows[4].Cells[2].Style.ForeColor = Color.Red;
     }

     private DataTable Source()
     {
         DataTable mydt = new DataTable();
         mydt.Columns.Add("姓名");
         mydt.Columns.Add("年龄");
         mydt.Columns.Add("分数");
         String[,] str = new String[,] { { "张三", "21", "90" }, { "李四", "22", "93" }, { "王五", "23", "99" }, { "赵六", "28", "80" }, { "孙七", "27", "86" } };

         for (int i = 0; i < 5; i++)
         {
             DataRow dr = mydt.NewRow();
             dr[0] = str[i, 0];
             dr[1] = str[i, 1];
             dr[2] = str[i, 2];
             mydt.Rows.Add(dr);
         }
         return mydt;

     }
 }

本文来自 www.luofenming.com