stackoverflow的人們美好的一天,
我正在構建一個 GUI,在這個 GUI 中我有一個顯示來自資料庫的資料的 datagridview。但是,當該行的第一列包含字串“Aborted”時,我正在尋找一種將整行的顏色更改為紅色的方法。
我已經嘗試找到解決方案,但是所有示例都是使用整數而不是字串的條件。
這是我當前的著色代碼:
private void datagridview1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1 && e.Value as string == "Aborted")
{
var style = datagridview1.Rows[e.RowIndex].DefaultCellStyle;
style.BackColor = Color.Red;
style.ForeColor = Color.White;
}
}
但是,這不會改變包含 Aborted 值的列或整行的顏色,甚至不會給出錯誤訊息......
datagridview1即使在它旁邊的事件屬性中CellFormatting也顯示datagridview1_CellFormatting,所以它肯定是系結到資料網格視圖的。
datagridview1 的螢屏截圖 事件屬性
資料網格視圖的螢屏截圖在 此處輸入影像描述
有人對此有解決方案嗎?我完全不知道出了什么問題。
編輯: @Jimi 示例的錯誤錯誤的快速截圖
uj5u.com熱心網友回復:
您正在操作錯誤的樣式物件。嘗試這個:
private void datagridview1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1 && e.Value as string == "Aborted")
{
e.CellStyle.BackColor = Color.Red;
e.CellStyle.ForeColor = Color.White;
}
}
uj5u.com熱心網友回復:
如果您只想為“中止”的列著色,Oliver 的解決方案效果很好,但是為整行著色的解決方案如下(非常感謝 Reddit 的u/JTarsier)
// Use the event CellFormatting from Datagridview > Properties > Events
private void datagridview1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// Use this one liner to check which number is associated with which column
//(so you don't make the mistake of trying to use the wrong column like me ._.)
// Debug.WriteLine($"{e.ColumnIndex} : '{e.Value}'");
if (e.ColumnIndex == 0 && e.Value as string == "Aborted")
{
var style = datagridview1.Rows[e.RowIndex].DefaultCellStyle;
style.BackColor = Color.Red;
style.ForeColor = Color.White;
}
}
感謝所有的幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516757.html
標籤:C#表格数据网格视图
