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行顏色的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: