C#编程-76:DataGridView当前行显示不同颜色_彭世瑜_新浪博客
发布日期:2021-07-01 06:17:57 浏览次数:2 分类:技术文章

本文共 1258 字,大约阅读时间需要 4 分钟。

var       值类型
object 引用类型
实现效果:
实现代码:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9.  
  10. namespace DataGridViewColor
  11. {
  12.     public partial class Form1 : Form
  13.     {
  14.         public Form1()
  15.         {
  16.             InitializeComponent();
  17.         }
  18.  
  19.         private void Form1_Load(object sender, EventArgs e)
  20.         {
  21.             // TODO:  这行代码将数据加载到表“companyDataSet.clerk”中。您可以根据需要移动或删除它。
  22.             this.clerkTableAdapter.Fill(this.companyDataSet.clerk);
  23.  
  24.         }
  25.  
  26.         private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
  27.         {
  28.             //判断索引有效范围
  29.             if(e.RowIndex>=dataGridView1.Rows.Count-1) return;
  30.  
  31.             //存储原来的颜色值
  32.             Color oldForeColor = new Color();
  33.             Color oldBackColor = new Color();
  34.  
  35.             //判断传入的行是否为当前选中行
  36.             var row=dataGridView1.Rows[e.RowIndex];
  37.             if (row == dataGridView1.CurrentRow)
  38.             {
  39.                 //设置前景色
  40.                 if (row.DefaultCellStyle.ForeColor != Color.White)
  41.                 {
  42.                     oldForeColor = row.DefaultCellStyle.ForeColor;
  43.                     row.DefaultCellStyle.ForeColor = Color.White;
  44.                 }
  45.                 //设置背景色
  46.                 if (row.DefaultCellStyle.BackColor != Color.Blue)
  47.                 {
  48.                     oldBackColor = row.DefaultCellStyle.BackColor;
  49.                     row.DefaultCellStyle.BackColor = Color.Blue;
  50.                 }
  51.  
  52.             }
  53.             //未选中则恢复原来的颜色
  54.             else
  55.             {
  56.                 row.DefaultCellStyle.ForeColor = oldForeColor;
  57.                 row.DefaultCellStyle.BackColor = oldBackColor;
  58.             }
  59.         }
  60.     }
  61. }

转载地址:https://pengshiyu.blog.csdn.net/article/details/109661798 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C#编程-77:DataGridView绘制行序号_彭世瑜_新浪博客
下一篇:C#编程-75:DataGridView直接修改数据库_彭世瑜_新浪博客

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月16日 11时27分31秒