我有一个数据网格视图,想知道是否可以只突出显示包含特定列值的特定行。DataGridView中的不同颜色的线(DGV)
所以我想所有的行默认为黑色的白色文本,除了任何具有指定列的行等于FUJI/UNIVERSAL
。对于这一行,我希望它是带有黑色文字的黄色。
所以我的问题是......这是可能的吗?如果是这样,怎么样?
我有一个数据网格视图,想知道是否可以只突出显示包含特定列值的特定行。DataGridView中的不同颜色的线(DGV)
所以我想所有的行默认为黑色的白色文本,除了任何具有指定列的行等于FUJI/UNIVERSAL
。对于这一行,我希望它是带有黑色文字的黄色。
所以我的问题是......这是可能的吗?如果是这样,怎么样?
最好的地方就是DataGridView的RowPrePaint事件。
这里是你如何实现这一目标。
void dataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == "YourConditionalValue")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
}
}
处理DataGridView
控件的OnPaint事件。
解析所有行,并在具有您要查找的信息的行上设置颜色。
一些示例代码:
int specificColumnIndex = 5;
const string FUJIUNIV = "FUJI/UNIVERSAL";
const Color cFUJIBACK = Color.Yellow;
const Color cFUJITEXT = Color.Black;
public Form1() {
InitializeComponent();
dataGridView1.Paint += new PaintEventHandler(DataGridView_Paint);
}
private void DataGridView_Paint(object sender, PaintEventArgs e) {
foreach (DataGridViewRow row in dataGridView1.Rows) {
if (row.Cells[specificColumnIndex].Value.ToString() == FUJIUNIV) {
foreach (DataGridViewCell cell in row.Cells) {
cell.Style.BackColor = cFUJIBACK;
cell.Style.ForeColor = cFUJITEXT;
cell.Style.SelectionBackColor = Color.Gold;
}
}
}
}
}
例如通过处理OnCellFormatting
事件。
下面是我的一个旧的WinForms爱好项目中的一段代码,它完全是这样。它也再次教给我评论的重要性(我现在还没有机会记住它)。
我确信你可以适应你的目的。
private void sheetCalendar_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (CurrentRota == null)
{
return;
}
/* A word of explanation is needed. We retrieve the DataGridView from sender
* and we access the cell in question directly.
* MSDN advices against it -
* "to avoid performance penalties When handling this event,
* access the cell through the parameters of the event handler
* rather than accessing the cell directly."
*
* The problem is that we don't want to set the same colour to the same cell
* over and over again.
* And e.CellStyle always "forgets" what colour the call had had! */
var dgrid = sender as DataGridView;
var _col = e.ColumnIndex;
var _row = e.RowIndex;
var _highlight = (((Rota) sheetCalendar.Rows[e.RowIndex].DataBoundItem).Monday ==
CurrentRota.Monday);
var color = _highlight ?
Settings.Default.DGRIDCalendar_CurrentlyEditedBackColor :
SystemColors.Window;
if (dgrid[_col, _row].Style.BackColor != color)
dgrid[_col, _row].Style.BackColor = color;
}
最简单和最短的代码。谢谢! – theNoobGuy