[英]how to change the color in datagridview row when i check the checkbox in C# windows applications?
当我在C#Windows应用程序中选中复选框时,如何更改datagridview行中的颜色?我在datagridview的标题列中有一个用于选择一个复选框的代码,它检查所有复选框并更改datagridview行中的背景颜色,但是我想要选中一个复选框,相应的datagridview行将更改颜色,请帮助我
private void Form1_Load_1(object sender, EventArgs e)
{
this.ckBox.CheckedChanged += new System.EventHandler(this.ckBox_CheckedChanged);
this.dataGridView1.Controls.Add(ckBox);
}
void ckBox_CheckedChanged(object sender, EventArgs e)
{
for (int j = 0; j < this.dataGridView1.RowCount; j++)
{
this.dataGridView1[2, j].Value = this.ckBox.Checked;
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell check = row.Cells["Chk"] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(check.Value) == true)
row.DefaultCellStyle.BackColor = Color.Wheat;
else
row.DefaultCellStyle.BackColor = Color.White;
}
this.dataGridView1.EndEdit();
}
将CheckBox
添加到标题的代码已经很好地工作了。
要将CheckBox
右对齐,您需要计算位置,如下所示:
ckBox.Location = new Point(rect.Right - ckBox.Width - 4, rect.Top + 4);
我添加了一些像素填充。 您将需要使列足够宽,以防止CheckBox
与标题文本重叠。
但是,每当用户更改列的宽度或列顺序或添加新列时,您都需要重复对齐 。
因此,我建议将对齐代码移到可以在需要时调用的函数中:
void layoutCheckBox()
{
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(2, -1, true);
ckBox.Location = new Point(rect.Right - ckBox.Width - 4, rect.Top + 4);
}
例如这里:
private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
layoutCheckBox();
}
然后是一些,如前所述; 取决于用户可以做什么。
至于CheckChanged
代码,如果Chk
列中的单元格确实都是DataGridViewCheckBoxCells
,它似乎可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.