简体   繁体   English

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

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

I have two columns of check boxes for 'Build' and 'Publish'. 我有两列用于“生成”和“发布”的复选框。 I want each of the headers to display 'Build [ ]" and 'Publish [ ]", where [ ] is a check box that allow the user to select or deselect all check boxes in the respective column. 我希望每个标题都显示“ Build []”和“ Publish []”,其中[]是一个复选框,允许用户选择或取消选择相应列中的所有复选框。 PRIORITY: How can I achieve this without creating new classes or adding images? 优先级:如何在不创建新类或添加图像的情况下实现这一目标? LAST RESORT: If this is not possible, can you guide me to construct the appropriate classes? 最后的解决方法:如果不可能,您可以指导我构造适当的类吗? Thanks in advance! 提前致谢!

You can use two regular CheckBoxes and add them to the DataGridView : 您可以使用两个常规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;

To keep them positioned in the ColumnHeaders use code like this: 要使它们位于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;
}

Use appropriate indices to meet your columns and offsets to place them a little more to the right, if needed. 如果需要,请使用适当的索引来满足您的列和偏移量的要求,以将它们向右移一些。

You will have to implement your logic to prevent value changes in the DGV as you normally would, eg in the Validating event.. 您将必须实现逻辑来防止DGV中的值更改,例如在Validating事件中那样。

Update: 更新:

This event is probably a good or even better alternative as it doesn't get called so often; 此事件可能是一个很好的选择,甚至是更好的选择,因为它很少被调用。 it'll do, at least if you only need to adapt the position after the user changes the column widths: 至少在用户更改列宽后仅需要调整位置的情况下,它就会这样做:

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;
}

If columns can also be deleted, added or reordered these events would also have to be scripted: ColumnRemoved, ColumnAdded, ColumnDisplayIndexChanged . 如果还可以删除,添加或重新排序列,则还必须编写以下事件脚本: ColumnRemoved, ColumnAdded, ColumnDisplayIndexChanged All work with the above 2 lines. 都适用于以上两行。

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

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