我有一个填充了数据的dataGridView对象.我想点击一个按钮,让它改变单元格背景的颜色.这就是我现在拥有的
foreach(DataGridViewRow row in dataGridView1.Rows)
{
foreach(DataGridViewColumn col in dataGridView1.Columns)
{
//row.Cells[col.Index].Style.BackColor = Color.Green; //doesn't work
//col.Cells[row.Index].Style.BackColor = Color.Green; //doesn't work
dataGridView1[col.Index, row.Index].Style.BackColor = Color.Green; //doesn't work
}
}
Run Code Online (Sandbox Code Playgroud)
所有这三个都会导致表格以重叠的方式重新绘制,并且尝试重新调整表格的大小变得一团糟.单击单元格时,值仍然突出显示,背景颜色不会更改.
问:如何在表存在后更改单个单元格的背景颜色?
我想DataGridView在编辑时在单元格周围绘制一个红色边框.
我设法在所选单元格周围绘制一个红色边框,而不是使用此代码编辑它:
private void Form1_Load(object sender, EventArgs e)
{
this.Width = 650;
this.Height = 250;
dataGridView1.Left = 5;
dataGridView1.Top = 5;
dataGridView1.Width = 600;
dataGridView1.Height = 175;
DataTable dt = new DataTable("Test Table");
dt.Columns.Add("Column 1");
dt.Columns.Add("Column 2");
dt.Columns.Add("Column 3");
dt.Columns.Add("Column 4");
dt.Columns.Add("Column 5");
dt.Rows.Add(dt.NewRow());
dt.Rows.Add(dt.NewRow());
dt.Rows.Add(dt.NewRow());
dt.Rows.Add(dt.NewRow());
dt.Rows.Add(dt.NewRow());
dataGridView1.DataSource = dt;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.MultiSelect = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White;
dataGridView1.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.dataGridView1_CellPainting);
dataGridView1.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.dataGridView1_EditingControlShowing);
}
private void dataGridView1_CellPainting(object …Run Code Online (Sandbox Code Playgroud)