您可以使用两个常规的CheckBoxes 并将它们添加到DataGridView:
cbx_Build.Parent = dataGridView1;
cbx_Build.Location = new Point(0, 3);
cbx_Build.BackColor = SystemColors.Window;
cbx_Build.AutoSize = false;
cbx_Publish.Parent = dataGridView1;
cbx_Publish.Location = new Point(0, 3);
cbx_Publish.BackColor = SystemColors.Window;
cbx_Publish.AutoSize = false;
要将它们定位在 ColumnHeaders 中,请使用如下代码:
dataGridView1.CellPainting += dataGridView1_CellPainting;
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == BuildIndex && e.RowIndex == 0) cbx_Build.Left = e.CellBounds.Left;
if (e.ColumnIndex == PubIndex && e.RowIndex == 0) cbx_Publish.Left = e.CellBounds.Left;
}
如果需要,使用适当的索引来满足您的列和偏移量,以便将它们放置在更右侧。
您必须像往常一样实施您的逻辑来防止 DGV 中的值发生变化,例如在Validating 事件中..
更新:
此事件可能是一个不错的选择,甚至是更好的选择,因为它不会被如此频繁地调用;它会做,至少如果您只需要在用户更改列宽后调整位置:
private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
cbx_Build.Left = dataGridView1.Columns[BuildIndex].HeaderCell.ContentBounds.Left;
cbx_Publish.Left = dataGridView1.Columns[PubIndex].HeaderCell.ContentBounds.Left;
}
如果列也可以删除、添加或重新排序,这些事件也必须编写脚本:ColumnRemoved, ColumnAdded, ColumnDisplayIndexChanged。以上两行都适用。