C#開發(fā)WinForm根據(jù)條件改變DataGridView行顏色
根據(jù)條件改變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"))
{
// 設(shè)置單元格的背景色
dr.DefaultCellStyle.BackColor = Color.Yellow;
// 設(shè)置單元格的前景色
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 '數(shù)量' 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;
}
}
}示例程序下載地址:點此下載
到此這篇關(guān)于C#開發(fā)WinForm根據(jù)條件改變DataGridView行顏色的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#如何優(yōu)雅的對WinForm窗體應(yīng)用程序進行權(quán)限控制
經(jīng)常會出現(xiàn)winfrom頁面需要加載權(quán)限樹,下面這篇文章主要給大家介紹了關(guān)于C#如何優(yōu)雅的對WinForm窗體應(yīng)用程序進行權(quán)限控制的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11
C#中調(diào)用SAPI實現(xiàn)語音合成的2種方法
這篇文章主要介紹了C#中調(diào)用SAPI實現(xiàn)語音合成的2種方法,本文直接給出示例代碼,需要的朋友可以參考下2015-06-06
C#連接操作 MySQL 數(shù)據(jù)庫實例(使用官方驅(qū)動)
這篇文章主要介紹了C#連接操作 MySQL 數(shù)據(jù)庫實例(使用官方驅(qū)動),本文講解了C#中的Mysql連接方法和SQL操作方法,需要的朋友可以參考下2015-02-02
C#實現(xiàn)的圖片、string相互轉(zhuǎn)換類分享
這篇文章主要介紹了C#實現(xiàn)的圖片、string相互轉(zhuǎn)換類分享,本文直接給出類代碼,包含相互轉(zhuǎn)換的方法,需要的朋友可以參考下2015-03-03
C#實現(xiàn)PDF簽名時添加時間戳的2種方法(附VB.NET代碼)
在PDF添加簽名時,支持添加可信時間戳來保證文檔的法律效應(yīng)。本文,將通過C#程序代碼介紹如何添加可信時間戳,可通過2種方法來實現(xiàn)。感興趣的可以了解一下2021-05-05
C#調(diào)用QQ_Mail發(fā)送郵件實例代碼兩例
這篇文章介紹了C#調(diào)用QQ_Mail發(fā)送郵件的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04

