繁体   English   中英

DataGridView列标题以包含文本和复选框

[英]DataGridView Column Header to include text AND check box

我有两列用于“生成”和“发布”的复选框。 我希望每个标题都显示“ Build []”和“ Publish []”,其中[]是一个复选框,允许用户选择或取消选择相应列中的所有复选框。 优先级:如何在不创建新类或添加图像的情况下实现这一目标? 最后的解决方法:如果不可能,您可以指导我构造适当的类吗? 提前致谢!

您可以使用两个常规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 都适用于以上两行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM