C#设置并从DataGridView重置颜色
大家好,我使用datagridviewcell.style属性为我单击的每个单元格设置背景颜色。
if (e.RowIndex < 0 || e.RowIndex == dataMenu.NewRowIndex)
{
return;
}
var dataGridViewCellStyle = new DataGridViewCellStyle(dataMenu.DefaultCellStyle)
{
BackColor = Color.CornflowerBlue
};
dataMenu[e.ColumnIndex, e.RowIndex].Style = dataGridViewCellStyle;
,但是现在我希望,如果我单击同一列中的另一个单元格,整列将背景颜色更改为白色,然后将下一个单元格设置为'color.cornflowerblue'
我想避免同一列中的多个单元格具有相同的颜色。 对于每一列,只能在一个单元格上设置颜色!
不可能做这样的事情: 如您在“ montag”列中看到的那样,可以更改多个单元格的颜色。 我希望,如果我现在单击“ montag”中的另一个单元格,则应重置整列,并在新的聚焦单元格上设置颜色。
我已经尝试了此代码:
dataMenu.Columns[e.ColumnIndex].DefaultCellStyle.BackColor = Color.Red;
但是,只有我在这篇文章顶部写的第一个背色集函数后面的后彩色。
Hey Guys i use the DataGridViewCell.Style property to set the Background color for each Cell i clicked on it.
if (e.RowIndex < 0 || e.RowIndex == dataMenu.NewRowIndex)
{
return;
}
var dataGridViewCellStyle = new DataGridViewCellStyle(dataMenu.DefaultCellStyle)
{
BackColor = Color.CornflowerBlue
};
dataMenu[e.ColumnIndex, e.RowIndex].Style = dataGridViewCellStyle;
But now i want that if i click on a other Cell in the same Column, that the whole Column change the Background Color to White before it set the next Cell to 'Color.CornflowerBlue'
I want to avoid that multiple Cells in the same Column can be have the same color.
For each Column it should only be possible to set the color on one cell!
It should not possible to do something like this:
As you can see in the Column "Montag" it was possible to change the colors for multiple cells.
I want that if i click now on a other Cell in "Montag" then the whole Column should be resetted and set the Color on the new focused Cell.
i already tried this piece of code:
dataMenu.Columns[e.ColumnIndex].DefaultCellStyle.BackColor = Color.Red;
But this change only the BackColor behind the first BackColor Set function i wrote on the Top of this post.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在设置单元格的样式之前,请在同一列上清除其他单元格的样式。它只需要对您的初始代码进行一些修改,
我在重现您的问题时注意到了一些副作用。决定提供其他建议,以防万一
SET
selectionbackColor
和selectionforecolor
的默认单元格样式与未选择状态相同。您也可以在设计师中进行。在Designer中选择您的数据网格视图。在属性网格中修改
defaulcellstyle
属性。当您在代码中设置单元格的
样式
时,请执行相同的操作。如果您需要取消选择已经选择的单元格,则可以使用以下代码。如果单击选定的单元格,则取消选择。
Before you set the style of a cell, clear the style of other cells on the same column. All it takes is a little modification of your initial code
I noticed some side-effects while reproducing your issue. Decided to give additional recommendations, just in case
Set
SelectionBackColor
andSelectionForeColor
of default cell style same as that of unselected state.You can do it in Designer as well. Select your data grid view in designer. In property grid modify
DefaulCellStyle
property.Do the same thing when you set
Style
of a cell in code.If you need deselect already selected cell then you can use following code. It deselectes if selected cell is clicked.