据我理解您的问题,您想要更改可编辑的datagridview
中的单元格颜色?
您可以通过使用datagridview
的DataGridViewCellFormattingEvent
事件,并检查列是否为readonly
,然后更改datagridviewcell
的背景来实现此目的。
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (!dgv.Columns[e.ColumnIndex].ReadOnly)
{
e.CellStyle.BackColor = Color.Yellow;
}
}
输出:
void dataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
foreach ( DataGridViewRow row in dataGridView1.Rows )
{
if ( row.Cells["myColumn"].Value == "editable" )
row.Cells["myColumn"].Style.BackColor = Color.Yellow;
else
row.Cells["myColumn"].Style.BackColor = Color.Red;
}
}
你也可以重写 paint 方法,如 这里 所述。
object' does not contain a definition for 'Cells' and no extension method 'Cells' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
,针对rows.Cells。 - technorow.Cells[1]
访问它。 - Bluevalue
是否包含文本“editable”。 - Shift 'n Tab这只是一个示例代码,使一列可编辑,dgvSample是您在表单中添加的DataGridView。在这里,我已经使所有奇数列可编辑。因此,以同样的方式,您可以拥有带复选框的隐藏列,并检查其是否可编辑并实现相同的效果。
dgvSample.AllowUserToAddRows = false;
dgvSample.AllowUserToDeleteRows = false;
for (int i = 0; i <= 10; i++)
{
string[] values = new string[] { "1", "Name" };
dgvSample.Rows.Add(values);
if (i % 2 == 0)
{
DataGridViewRow r = dgvSample.Rows[dgvSample.Rows.Count - 1];
r.ReadOnly = true;
}
else
{
r.DefaultCellStyle.BackColor = Color.Yellow;
}
}
if语句
中的dgv
前面添加了!
。 - Shift 'n Tabreadonly
属性。 - Shift 'n TabReadOnly=false
设置为3列。只有1个单元格显示为黄色。其他2个单元格只有在我点击它们后才会变成黄色。 - techno