private void Form1_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("A"); dt.Columns.Add("B"); dt.Columns.Add("C"); dt.Columns.Add("D"); dt.Rows.Add(new object[] { "", "", "", "" }); dt.Rows.Add(new object[] { "", "", "", "" }); dt.Rows.Add(new object[] { "", "", "", "" }); this.dataGridView1.DataSource = dt; dataGridView1.AllowUserToAddRows = false;//禁止自动生成行 dataGridView1.ColumnHeadersVisible = false;//隐藏列头 }设置方法,通过调用方法实现dataGridView单元格合并功能
时间: 2024-03-28 20:40:57 浏览: 90
以下是 dataGridView 单元格合并的实现方法:
private void MergeCells()
{
// 第一步:合并 A 列中相邻的相同单元格
for (int rowIndex = dataGridView1.Rows.Count - 2; rowIndex >= 0; rowIndex--)
{
DataGridViewRow currentRow = dataGridView1.Rows[rowIndex];
DataGridViewRow previousRow = dataGridView1.Rows[rowIndex + 1];
if (currentRow.Cells[0].Value == previousRow.Cells[0].Value)
{
currentRow.Cells[0].RowSpan = previousRow.Cells[0].RowSpan < 1 ? 2 : previousRow.Cells[0].RowSpan + 1;
previousRow.Cells[0].Visible = false;
}
}
// 第二步:合并 B、C、D 列中相邻的相同单元格
for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++)
{
DataGridViewRow currentRow = dataGridView1.Rows[rowIndex];
for (int columnIndex = 1; columnIndex < dataGridView1.Columns.Count; columnIndex++)
{
DataGridViewCell currentCell = currentRow.Cells[columnIndex];
DataGridViewCell previousCell = currentRow.Cells[columnIndex - 1];
if (currentCell.Value == previousCell.Value && currentCell.Visible && previousCell.Visible)
{
previousCell.ColumnSpan = previousCell.ColumnSpan < 1 ? 2 : previousCell.ColumnSpan + 1;
currentCell.Visible = false;
}
}
}
}
在 Form1_Load 方法中调用 MergeCells 方法即可实现单元格合并功能。
阅读全文