[英]Dynamically cell color change in DataGridView
我正在開發數據庫應用程序。 其中一些列是文本列,其中一列是日期。 我想將列的日期與系統日期進行比較,並且要在列的日期值小於系統日期時將單元格背景顏色變為紅色。 在給定的代碼下方,我嘗試但不起作用。
private void EMIDGVAdm_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.EMIDGVAdm.Columns[e.ColumnIndex].DataPropertyName == "Date_1")
{
var EMIDate = Convert.ToDateTime(EMIDGVAdm.Rows[e.RowIndex].Cells["Date_1"].Value);
if (EMIDate <= DateTime.Now)
{
e.CellStyle.BackColor = Color.Red;
//e.CellStyle.ForeColor = Color.Red;
}
}
}
如果不需要時間部分,請使用Today
。 try catch
處理日期字段中可能為null的情況。 必須在var EMIDate
行中使用gridview列集合名稱,該名稱可能與DataPropertyName不同。 因此,對於您的工作過程中的gridview來說,它們可能是相同的。
分析了OP的項目。 似乎該代碼不會讀取看不見的列,因此不得不加寬DataGridView和面板以顯示Date_1列而無需滾動。 另外,DataPropertyName沒有下划線。 調整后的設計和代碼工作:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "Date 1")
try
{
var EMIDate = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells["date1DataGridViewTextBoxColumn"].Value);
if (EMIDate <= DateTime.Today)
{
e.CellStyle.BackColor = Color.Red;
}
}
catch
{
}
}
找到一個似乎被錯誤命名的文本框。 為了與其他控件的命名保持一致,可能textBox6應該是txtEMI6。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.