[英]Change datagridview cell color by clicking in c#(winform)
我在表单上有一个数据网格。
我想要那个
当我点击任何行上的任何单元格时
例如,单元格背面颜色可以更改为红色。
我怎样才能做到这一点...
使用单元格点击事件
在事件中只是将cell.backcolor分配给color.red
private void GridView_CellClick(object sender,DataGridViewCellEventArgs e)
private void GridView_CellClick(object sender, DataGridViewCellEventArgs e){
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.BackColor = Color.Red;
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle;
}
您可以更改DefaultCellStyle。 例如:
...
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
...
DataGridViewCell cell;
cell = datagridview1[0,0]; // location of cell
cell.Style.BackColor = Color.LimeGreen; // or whatever color you want
这可以使用索引放置在循环等中。
我建议在Cell_Enter事件中设置它
要么
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.Value != null)
{
if (condition)
e.CellStyle.BackColor = Color.FromArgb(255, 160, 160);
}
}
从 2022 年开始更新,使用 Visual Studio 2022,到用户@Umesh CHILAKA 的正确答案。
DataGridViewCellStyle 具有 BackColor 属性,这意味着您可以直接访问它,因此您可以考虑使用以下内容,因为它也可以工作:
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red
此方法的另一个优点是您无需创建另一个 object DataGridViewCellStyle。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.