300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > DataGridView:根据条件改变单元格的颜色

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

时间:2021-02-03 03:03:04

相关推荐

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

根据条件改变DataGridView行的颜色可以使用RowPrePaint事件。

示例程序界面如下:

示例程序代码如下:

1 using System; 2 using System.Collections.Generic; 3 using ponentModel; 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 DgvChangeColor14 {15public partial class Form1 : Form16{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 else45 {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 try60 {61 conn.Open();62 adapter.Fill(dt);63 }64 catch (Exception ex)65 {66 MessageBox.Show(ex.Message);67 }68 finally69 {70 conn.Close();71 }72 return dt;73 }74}75 }

示例程序下载地址:/s/1sm2eSlZ

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。