相邻的单元格(顶部和左)选择
问题描述:
图片表示对上述问题,当绘制了自定义绘制边框:相邻的单元格(顶部和左)选择
下面是我使用的周围绘制边框选择单元格代码:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex > 0 && e.RowIndex > -1)
{
if (e.Value != null && (!e.Value.Equals("0")) && (!e.Value.Equals("-")))
{
double d = Convert.ToDouble(e.Value);
if (e.ColumnIndex == 2)
{
int limit = Convert.ToInt16(numericUpDown1.Value);
if (d > limit)
{
int pWidth = 1;
Pen p = new Pen(Color.Red, pWidth);
e.PaintBackground(e.CellBounds, true);
e.PaintContent(e.CellBounds);
int x = e.CellBounds.Left – pWidth;
int y = e.CellBounds.Top – pWidth;
int w = e.CellBounds.Width;
int h = e.CellBounds.Height;
e.Graphics.DrawRectangle(p, x,y,w,h);
e.Handled = true;
}
}
}
}
}
有没有办法让它们不消失?它不会发生在底部和右边界。我已经试过几件事情包括:
- 禁用边框和拉丝我自己的所有细胞(同样的问题)
- 调整绘制矩形是细胞内(不喜欢看)
- 处理CellEnter/CellLeave/CellClick到.Invalidate的行和列,企图获取自定义边框细胞在上面
答
我尝试了TAWS答案(能评当时),它没有解决问题,但让我思考。我需要废止这些细胞的任何时间被吸引其他细胞,使我增加了事件处理程序如下:
- CellMouseDown
- CellMouseUp
- 的SelectionChanged
- Form_Activated
,而不是与使邻近单元格无效,因为它似乎没有工作,我使该列的显示列矩形失效,因为它是当前唯一具有自定义有边界单元格的列。
答
的问题是两个油漆事件是相互矛盾的,重新油漆:
- 你CellPaint绘制漂亮的红色边框..
- ..和的是,该系统绘制选定单元格摧毁你的红色边框相邻小区后。
其实这更是雪上加霜,这取决于你如何移动的选择,尤其是当你将其向上或向下,因为现在不仅选择是画也是以前的选择恢复,摧毁了红色的边框上方或下方的细胞也是如此!
我不知道为什么会发生这种不对称;也许这是旧的DrawRectanlge错误,它往往会将大小减去一个。 (这就是为什么你不能绘制一个大小为1的矩形;你需要填充它!)或者也许事件的顺序有些奇怪..
就是这样,你会解决问题仅仅是使用InvalidateCell
迫使受影响的细胞的一个新的画:
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridViewCell cell = dataGridView1.CurrentCell;
if (cell.ColumnIndex < dataGridView1.ColumnCount - 1)
{
dataGridView1.InvalidateCell(cell.ColumnIndex + 1, cell.RowIndex);
if (cell.RowIndex > 0)
dataGridView1.InvalidateCell(cell.ColumnIndex + 1, cell.RowIndex - 1);
if (cell.RowIndex < DGV.ColumnCount -1)
dataGridView1.InvalidateCell(cell.ColumnIndex + 1, cell.RowIndex + 1);
}
}
你可能想它,进而优化你的所有者绘制列..