您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“C#開(kāi)發(fā)WinForm中怎么根據(jù)條件改變DataGridView行顏色”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C#開(kāi)發(fā)WinForm中怎么根據(jù)條件改變DataGridView行顏色”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。
根據(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["項(xiàng)目代碼"].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 '項(xiàng)目代碼',XIANGMUMC AS '項(xiàng)目名稱(chēng)', DANJIA AS '單價(jià)',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; } } }
讀到這里,這篇“C#開(kāi)發(fā)WinForm中怎么根據(jù)條件改變DataGridView行顏色”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。