突出显示DataGridView中的选定单元格?
问题描述:
在我的代码如下,当用户右键单击我的DataGridView中的一个单元格时,我显示了一个上下文菜单。我也喜欢用户右键单击的单元格来更改背景颜色,以便他们可以看到他们“单击右键选择”的单元格。有没有办法给我的代码添加一些东西,以便发生这种情况?突出显示DataGridView中的选定单元格?
private void dataGridView2_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu m = new ContextMenu();
MenuItem mnuCopy = new MenuItem("Copy");
mnuCopy.Click += new EventHandler(mnuCopy_Click);
m.MenuItems.Add(mnuCopy);
int currentMouseOverRow = dataGridView2.HitTest(e.X, e.Y).RowIndex;
m.Show(dataGridView2, new Point(e.X, e.Y));
}
}
答
很显然,你已经入侵了我的工作站,并且看到了我最近的一些工作。我夸大了一点,因为我没有做你想做的事情,只是稍微调整了我的能力。
我会修改您的MouseClick
事件以获得DGV的CurrentCell
。一旦拥有它,请将CurrentCell
的Style
属性与您想要的SelectionBackColor
一起设置。事情是这样的:
// ...
DataGridView.HitTestInfo hti = dataGridView2.HitTest(e.X, e.Y);
if (hti.Type == DataGridViewHitTestType.Cell) {
dataGridView2.CurrentCell = dataGridView2.Rows[hti.RowIndex].Cells[hti.ColumnIndex];
dataGridView2.CurrentCell.Style = new DataGridViewCellStyle { SelectionBackColor = System.Drawing.Color.Yellow};
}
//...
以上是有点“空气代号Y”(换句话说,我还没有尝试用你的代码合并,并运行它),但我希望你的想法。请注意,我通过点击测试检查单元格是否被点击;如果你不这样做,并且用户不点击一个单元格,你可能会遇到一些问题。
现在有一个问题,此代码将更改SelectionBackColor
您右键单击的所有单元格。这很容易在DGV的CellLeave
来还原该属性:
private void dgvBatches_CellLeave(object sender, DataGridViewCellEventArgs e) {
dataGridView2.CurrentCell.Style = new DataGridViewCellStyle { SelectionBackColor = System.Drawing.SystemColors.Highlight };
}
我必须记住这样的视觉影响;感谢您提出这个问题。
对您的工作站进行黑客入侵很抱歉!哦,并且忽略办公室里隐藏的相机。另外,如果您收到来自NURV软件的名为加里温斯顿的人的电话,请挂断电话。谢谢!! – Kevin