2016-03-08 66 views
0

在我的C#datagridview中,我希望用户被确认他们确实已经单击了该单元格。DataGridView Mousedown和Mouseup单元格背景颜色变化不起作用

我正在使用datagridview的MouseDown和MouseUp事件。通过将单元格颜色更改为蓝色,代码可以正常运行MouseDown事件,但MouseUp事件不会将单元格的颜色更改为透明。

由此产生的功能是,我点击的所有单元格变为蓝色,并保持蓝色。

我没有正确调用Refresh方法吗?有没有更好的方法来实现相同的目标?

这里是我的代码:

private void Selector_dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 
     { 
      DataGridViewCellStyle CellStyle = new DataGridViewCellStyle(); 
      CellStyle.BackColor = Color.Blue; 
      Selector_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle; 
      Selector_dataGridView.Refresh(); 
     } 

     private void Selector_dataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) 
     { 
      DataGridViewCellStyle CellStyle = new DataGridViewCellStyle(); 
      CellStyle.BackColor = Color.Transparent; 
      Selector_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle; 
      Selector_dataGridView.Refresh(); 
     } 

回答

1

你只需要在MouseDown一行:

Selector_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = Color.Blue; 

而且在MouseUp回复:

Selector_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = Color.White; 
+1

这工作。它看起来像我不得不使用Color.White,我不能使用Color.Empty或Color.Transparent。谢谢! – TheBear

0

在你Selector_dataGridView_CellMouseUp情况下,尝试改变颜色空的,而不是透明的:

CellStyle.BackColor = Color.Empty; 
+0

它现在改变行为,但还是差了一点。当我单击另一个单元格时,单元格正确地变为“空”。所以有一个步骤滞后。我的刷新功能没有正确调用。我是否正确使用刷新? – TheBear

0

细胞释放鼠标处理程序将触发对任何一个细胞的小鼠指针在那个时候结束了。我假设你点击后将鼠标移离点击单元格。我会建议清除/刷新所有单元格在mouseup上透明,但如果您处理大量单元格,将会有点矫枉过正。

https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellmouseup(v=vs.110).aspx

+0

我在mouseup事件上放置了一个断点,它引用了正确的行和列索引。我怀疑我调用的刷新方法使用不正确。它的一些如何不重新绘制鼠标,但只有mousedown。 – TheBear