簡體   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