checkbox在datagridview外并有多个
时间: 2024-02-16 19:03:20 浏览: 21
如果 checkbox 不在 DataGridView 中,而是在其他地方,并且有多个 checkbox 需要与 DataGridView 的行一一对应,可以在 DataGridView 的 CellPainting 事件中绘制 checkbox,然后在 checkbox 的 CheckedChanged 事件中更新 DataGridView 的行数据。
以下是示例代码:
```csharp
private Dictionary<int, CheckBox> checkBoxes = new Dictionary<int, CheckBox>();
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
// 绘制 checkbox 列
if (e.RowIndex >= 0 && e.ColumnIndex == 0)
{
e.PaintBackground(e.CellBounds, true);
int rowIndex = e.RowIndex;
CheckBox checkbox;
if (!checkBoxes.TryGetValue(rowIndex, out checkbox))
{
checkbox = new CheckBox();
checkbox.Size = new Size(16, 16);
checkbox.CheckedChanged += new EventHandler(checkbox_CheckedChanged);
checkBoxes[rowIndex] = checkbox;
}
Point checkboxLocation = new Point(e.CellBounds.Left + (e.CellBounds.Width - checkbox.Width) / 2,
e.CellBounds.Top + (e.CellBounds.Height - checkbox.Height) / 2);
checkbox.Location = checkboxLocation;
checkbox.Checked = (bool)dataGridView1.Rows[rowIndex].Cells[1].Value;
e.Graphics.DrawRectangle(Pens.Black, checkboxLocation.X - 1, checkboxLocation.Y - 1,
checkbox.Width + 1, checkbox.Height + 1);
e.Handled = true;
}
}
private void checkbox_CheckedChanged(object sender, EventArgs e)
{
// 更新 DataGridView 的行数据
CheckBox checkbox = (CheckBox)sender;
int rowIndex = dataGridView1.CurrentCell.RowIndex;
dataGridView1.Rows[rowIndex].Cells[1].Value = checkbox.Checked;
}
```
注意:上述代码中,我假设 checkbox 的状态与 DataGridView 的第二列数据对应,所以在更新 DataGridView 的行数据时,我使用了 `dataGridView1.Rows[rowIndex].Cells[1].Value`,需要根据实际情况修改。另外,如果要设置 checkbox 的样式,可以通过修改 `checkbox.Appearance` 和 `checkbox.FlatStyle` 属性来实现。