DataGridView:根据条件改变单元格的颜⾊
根据条件改变DataGridView⾏的颜⾊可以使⽤RowPrePaint事件。
⽰例程序界⾯如下:
⽰例程序代码如下:
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
灵芝的功效作用4using System.Data;
5using System.Drawing;
6using System.Linq;办公室租用
7using System.Text;
8using System.Threading.Tasks;
9using System.Windows.Forms;
10using System.Configuration;
太阳能板安装
11using System.Data.SqlClient;
12
13namespace DgvChangeColor
14 {
15public partial class Form1 : Form
16 {
17public Form1()
18 {
19 InitializeComponent();
20 }
21
美丽照片
22string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
冯唐易老的典故23private void Form1_Load(object nder, EventArgs e)
24 {
25 DataTable dt = GetDataSource();
26this.DgvColor.DataSource = dt;另一位研究者
27 }
28
29private void DgvColor_RowPrePaint(object nder, DataGridViewRowPrePaintEventArgs e)
30 {
31if (e.RowIndex >= DgvColor.Rows.Count - 1)
32 {
33return;
34 }
35 DataGridViewRow dr = (nder as DataGridView).Rows[e.RowIndex];
36
37if (dr.Cells["项⽬代码"].Value.ToString().Trim().Equals("ACAC0001"))
38 {
39// 设置单元格的背景⾊
40 dr.DefaultCellStyle.BackColor = Color.Yellow;
41// 设置单元格的前景⾊
42 dr.DefaultCellStyle.ForeColor = Color.Black;
43 }
44el
45 {
46 dr.DefaultCellStyle.BackColor = Color.Blue;
47 dr.DefaultCellStyle.ForeColor = Color.White;
48 }
49 }
50
51private DataTable GetDataSource()
52 {常性
53 DataTable dt = new DataTable();
54 SqlConnection conn = new SqlConnection(strCon);
55string strSQL = "SELECT XIANGMUCDDM AS '项⽬代码',XIANGMUMC AS '项⽬名称', DANJIA AS '单价',SHULIANG AS '数量' FROM InPatientBillDt WHERE 就诊ID='225600'";
56 SqlCommand cmd = new SqlCommand(strSQL, conn);
dha什么牌子好57 SqlDataAdapter adapter = new SqlDataAdapter();
58 adapter.SelectCommand = cmd;
59try
60 {
61 conn.Open();
62 adapter.Fill(dt);
63 }
64catch (Exception ex)
65 {
66 MessageBox.Show(ex.Message);
67 }
68finally
69 {
70 conn.Clo();
71 }
72return dt;
73 }
74 }
75 }