WinForms DataGridView單元格合併:完整指南
在WinForms的DataGridView中合併儲存格,關鍵在於尋找和處理重複值。以下是逐步說明:
找重複值
定義一個輔助方法來比較單元格值的相等性:
bool IsTheSameCellValue(int column, int row) { DataGridViewCell cell1 = dataGridView1[column, row]; DataGridViewCell cell2 = dataGridView1[column, row - 1]; if (cell1.Value == null || cell2.Value == null) { return false; } return cell1.Value.ToString() == cell2.Value.ToString(); }
單元格繪製事件 (CellPainting)
在DataGridView的CellPainting事件中,調整合併儲存格的邊框樣式:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None; if (e.RowIndex < 0 || e.ColumnIndex < 0) return; if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex)) { e.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.None; } }
單元格格式化事件 (CellFormatting)
在CellFormatting事件中,處理合併儲存格的格式:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.RowIndex == 0) return; if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex)) { e.Value = ""; e.FormattingApplied = true; } }
窗體載入事件 (Form Loading)
停用自動列產生:
private void Form1_Load(object sender, EventArgs e) { dataGridView1.AutoGenerateColumns = false; }
透過上述步驟,您可以合併DataGridView中的儲存格,以實現所需的資料呈現效果。
以上是如何在 WinForms 中合併 DataGridView 儲存格?的詳細內容。更多資訊請關注PHP中文網其他相關文章!