简体   繁体   中英

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. 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 :

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:

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..

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 . All work with the above 2 lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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