简体   繁体   English

DataGridView Mousedown和Mouseup单元格背景颜色更改不起作用

[英]DataGridView Mousedown and Mouseup cell background color change doesn't work

On my C# datagridview, I want the user to be acknowledged that they have indeed clicked on the cell. 在我的C#datagridview上,我希望用户被确认他们确实单击了该单元格。

I am using the datagridview's MouseDown and MouseUp events. 我正在使用datagridview的MouseDown和MouseUp事件。 The code functions correctly for the MouseDown event, by changing the cell color to Blue, but the MouseUp event does not change the color of the cell back to Transparent. 通过将单元格的颜色更改为蓝色,该代码对于MouseDown事件可以正常运行,但是MouseUp事件不会将单元格的颜色更改为“透明”。

The resulting function is that all the cells I click on turn Blue, and stay Blue. 结果功能是,我单击的所有单元格都变为蓝色,并保持蓝色。

Am I not calling the Refresh method correctly? 我没有正确调用Refresh方法吗? Is there a better way to achieve the same thing? 有没有更好的方法来实现同一目标?

Here is my code: 这是我的代码:

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();
        }

You need just a line in MouseDown : 您在MouseDown只需要一行:

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

And revert back in MouseUp : 然后返回MouseUp

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

在您的Selector_dataGridView_CellMouseUp事件中,尝试将颜色更改为空而不是透明:

CellStyle.BackColor = Color.Empty;

The cell mouse up handler will fire on whichever cell the mouse pointer is over at that time. 单元格鼠标向上处理程序将在此时鼠标指针悬停的任何单元格上触发。 I'm assuming you are moving you mouse away from the clicked cell after clicking. 我假设您单击鼠标后会将鼠标从单击的单元格中移开。 I would suggest clearing/refreshing all cells to transparent on mouseup but which will be a little overkill if you are dealing with a lot of cells. 我建议在mouseup上将所有单元格清除/刷新为透明,但是如果您要处理许多单元格,这将有些过分。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM