我的项目中有DataGrid
选择模式:FullRowSelect
。如何在单击的单元格上绘制矩形(如ListView
中所选单元格上的矩形)?或者改变颜色?
答案 0 :(得分:0)
我通过处理CellFormatting事件来改变DataGridViews的颜色。我这样做是为了突出显示错误的行,或突出显示特定的列;
在我的表单init方法中,我有类似的东西;
dgvData.CellFormatting +=
new DataGridViewCellFormattingEventHandler(dgvData_CellFormatting);
,负责格式化的方法如下;
private void dgvData_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
bool inError = false;
// Highlight the row as red if we're in error displaying mode
if (e.RowIndex >= 0 && fileErrors != null && DisplayErrors)
{
// Add +1 to e.rowindex as errors are using a 1-based index
var dataErrors = (from err in fileErrors
where err.LineNumberInError == (e.RowIndex +1)
select err).FirstOrDefault();
if (dataErrors != null)
{
e.CellStyle.BackColor = Color.Red;
inError = true;
}
}
// Set all the rows in a column to a colour, depending on it's mapping.
Color colourToSet = GetBackgroundColourForColumn(dgvData.Columns[e.ColumnIndex].Name);
if (colourToSet != null && !inError)
e.CellStyle.BackColor = colourToSet;
}
为了对特定单元格执行此操作,您可能还需要在控件上处理MouseUp事件,然后使用数据网格视图的HitTestInfo来确定命中实际所在的单元格。