这篇文章介绍了C#开发WinForm根据条件改变DataGridView行颜色的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
根据条件改变DataGridView行的颜色可以使用RowPrePaint事件。
示例程序界面如下:
示例程序代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace DgvChangeColor
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = GetDataSource();
            this.DgvColor.DataSource = dt;
        }
        private void DgvColor_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex >= DgvColor.Rows.Count - 1)
            {
                return;
            }
            DataGridViewRow dr = (sender as DataGridView).Rows[e.RowIndex];
            if (dr.Cells["项目代码"].Value.ToString().Trim().Equals("ACAC0001"))
            {
                // 设置单元格的背景色
                dr.DefaultCellStyle.BackColor = Color.Yellow;
                // 设置单元格的前景色
                dr.DefaultCellStyle.ForeColor = Color.Black;
            }
            else
            {
                dr.DefaultCellStyle.BackColor = Color.Blue;
                dr.DefaultCellStyle.ForeColor = Color.White;
            }
        }
        private DataTable GetDataSource()
        {
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(strCon);
            string strSQL = "SELECT XIANGMUCDDM AS '项目代码',XIANGMUMC AS '项目名称', DANJIA AS '单价',SHULIANG AS '数量' FROM InPatientBillDt WHERE 就诊ID='225600'";
            SqlCommand cmd = new SqlCommand(strSQL, conn);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            try
            {
                conn.Open();
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return dt;
        }
    }
}示例程序下载地址:点此下载
到此这篇关于C#开发WinForm根据条件改变DataGridView行颜色的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
				 沃梦达教程
				
			本文标题为:C#开发WinForm根据条件改变DataGridView行颜色
				
        
 
            
        
             猜你喜欢
        
	     - user32.dll 函数说明小结 2022-12-26
 - c# 模拟线性回归的示例 2023-03-14
 - 如何使用C# 捕获进程输出 2023-03-10
 - 在C# 8中如何使用默认接口方法详解 2023-03-29
 - Unity3D实现渐变颜色效果 2023-01-16
 - Oracle中for循环的使用方法 2023-07-04
 - C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
 - WPF使用DrawingContext实现绘制刻度条 2023-07-04
 - .NET CORE DI 依赖注入 2023-09-27
 - Unity Shader实现模糊效果 2023-04-27
 
						
						
						
						
						
				
				
				
				