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

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

DataGridView:根据条件改变单元格的颜⾊
根据条件改变DataGridView⾏的颜⾊可以使⽤RowPrePaint事件。

⽰例程序界⾯如下:
⽰例程序代码如下:
1using System;
2using System.Collections.Generic;
3using ponentModel;
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 sender, EventArgs e)
24 {
25 DataTable dt = GetDataSource();
26this.DgvColor.DataSource = dt;
27 }
28
29private void DgvColor_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
30 {
31if (e.RowIndex >= DgvColor.Rows.Count - 1)
32 {
33return;
34 }
35 DataGridViewRow dr = (sender 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 }
44else
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);
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.Close();
71 }
72return dt;
73 }
74 }
75 }。

相关文档
最新文档