我有两列用于“构建”和“发布”的复选框。我希望每个标题都显示“构建 []”和“发布 []”,其中 [] 是一个复选框,允许用户选择或取消选择相应列中的所有复选框。优先级:如何在不创建新类或添加图像的情况下实现这一点?最后的手段:如果这是不可能的,你能指导我构建适当的类吗?提前致谢!
问问题
1352 次
1 回答
1
您可以使用两个常规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
. 所有与上述 2 行一起工作。
于 2014-09-15T17:22:32.250 回答