在使用DataGridView控件放置通知等信息時,會遇到標記「已讀」、「未讀」的問題。經過SQL語句查詢出的結果中,「已讀」、「未讀」會被放在一個專門的字段(DataGridView的列)中用來標記這個 條目的閱讀狀況。本文的目標就是要作到在顯示上區分當前用戶已讀和未讀的條目。函數
一、準備工做this
創建一個C#窗體應用程序,裏面放置一個Dock屬性設置爲Full的DataGridViewspa
二、程序代碼code
在Load函數中,模擬生成了一個數據源,處理DataGridView顯示狀態的代碼放在DataSourceChanged事件中,即每當DataSource從新被賦值時刷新DataGridView的顯示狀態。代碼中按IsRead列的值判斷該行數據是否爲「已讀」orm
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace test { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void FormMain_Load(object sender, EventArgs e) { //生成數據源 DataTable dtTestData = new DataTable(); dtTestData.Columns.Add("Title"); dtTestData.Columns.Add("Content"); dtTestData.Columns.Add("IsRead"); dtTestData.Rows.Add("標題1", "正文1", true); dtTestData.Rows.Add("標題2", "正文2", false); dtTestData.Rows.Add("標題3", "正文3", true); dtTestData.Rows.Add("標題4", "正文4", false); dtTestData.Rows.Add("標題5", "正文5", true); this.dgvTestData.DataSource = dtTestData; } /// <summary> /// 數據表內數據源發生變化 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvTestData_DataSourceChanged(object sender, EventArgs e) { for (int i = 0; i < dgvTestData.Rows.Count; i++) { string isRead = dgvTestData.Rows[i].Cells["IsRead"].Value.ToString(); if (isRead.ToLower().Trim() == "true") { //TODO 已讀處理 dgvTestData.Rows[i].DefaultCellStyle.ForeColor = Color.Black; dgvTestData.Rows[i].DefaultCellStyle.BackColor = Color.White; dgvTestData.Rows[i].DefaultCellStyle.Font = new Font("宋體", 9F, FontStyle.Regular); } else { //TODO 未讀處理 dgvTestData.Rows[i].DefaultCellStyle.ForeColor = Color.Black; dgvTestData.Rows[i].DefaultCellStyle.BackColor = Color.White; dgvTestData.Rows[i].DefaultCellStyle.Font = new Font("宋體", 9F, FontStyle.Bold | FontStyle.Underline); } } } } }
若是不須要對某行操做,而是隻須要對某個單元格作出樣式上的改變,能夠寫成下面這樣:事件
dgvTestData.Rows[i].Cells["XXX"].Style.ForeColor = Color.Black; dgvTestData.Rows[i].Cells["XXX"].Style.BackColor = Color.White; dgvTestData.Rows[i].Cells["XXX"].Style.Font = new Font("宋體", 9F, FontStyle.Regular);
三、運行示例string
根據IsRead列的值判斷指定行是否加粗加下劃線,效果以下圖:it
ENDio