本文小編為大家詳細介紹“C#開發WinForm中怎么根據條件改變DataGridView行顏色”,內容詳細,步驟清晰,細節處理妥當,希望這篇“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行顏色”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。