您的位置:首页 > 其它

DataGridView:根据条件改变单元格的颜色

2018-02-24 10:20 337 查看
根据条件改变DataGridView行的颜色可以使用RowPrePaint事件。

示例程序界面如下:



示例程序代码如下:

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.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.Configuration;
11 using System.Data.SqlClient;
12
13 namespace DgvChangeColor
14 {
15     public partial class Form1 : Form
16     {
17         public Form1()
18         {
19             InitializeComponent();
20         }
21
22         string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
23         private void Form1_Load(object sender, EventArgs e)
24         {
25             DataTable dt = GetDataSource();
26             this.DgvColor.DataSource = dt;
27         }
28
29         private void DgvColor_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
30         {
31             if (e.RowIndex >= DgvColor.Rows.Count - 1)
32             {
33                 return;
34             }
35             DataGridViewRow dr = (sender as DataGridView).Rows[e.RowIndex];
36
37             if (dr.Cells["项目代码"].Value.ToString().Trim().Equals("ACAC0001"))
38             {
39                 // 设置单元格的背景色
40                 dr.DefaultCellStyle.BackColor = Color.Yellow;
41                 // 设置单元格的前景色
42                 dr.DefaultCellStyle.ForeColor = Color.Black;
43             }
44             else
45             {
46                 dr.DefaultCellStyle.BackColor = Color.Blue;
47                 dr.DefaultCellStyle.ForeColor = Color.White;
48             }
49         }
50
51         private DataTable GetDataSource()
52         {
53             DataTable dt = new DataTable();
54             SqlConnection conn = new SqlConnection(strCon);
55             string strSQL = "SELECT XIANGMUCDDM AS '项目代码',XIANGMUMC AS '项目名称', DANJIA AS '单价',SHULIANG AS '数量' FROM InPatientBillDt WHERE 就诊ID='225600'";
56             SqlCommand cmd = new SqlCommand(strSQL, conn);
57             SqlDataAdapter adapter = new SqlDataAdapter();
58             adapter.SelectCommand = cmd;
59             try
60             {
61                 conn.Open();
62                 adapter.Fill(dt);
63             }
64             catch (Exception ex)
65             {
66                 MessageBox.Show(ex.Message);
67             }
68             finally
69             {
70                 conn.Close();
71             }
72             return dt;
73         }
74     }
75 }


示例程序下载地址:https://pan.baidu.com/s/1sm2eSlZ
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: