using System;
using System.Windows.Forms;
public class DataGridViewMergeCells : Form
{
private DataGridView dataGridView1;
public DataGridViewMergeCells()
{
dataGridView1 = new DataGridView();
dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(dataGridView1);
// 添加一些示例数据
dataGridView1.Rows.Add("A", "B", "C");
dataGridView1.Rows.Add("A", "B", "D");
dataGridView1.Rows.Add("E", "F", "G");
// 合并相同的单元格
MergeCells(dataGridView1);
}
private void MergeCells(DataGridView dgv)
{
for (int col = 0; col < dgv.Columns.Count; col++)
{
int currentRow = 0;
while (currentRow < dgv.Rows.Count - 1)
{
int mergeCount = 1;
while (currentRow + mergeCount < dgv.Rows.Count &&
dgv.Rows[currentRow].Cells[col].Value?.ToString() ==
dgv.Rows[currentRow + mergeCount].Cells[col].Value?.ToString())
{
mergeCount++;
}
if (mergeCount > 1)
{
dgv.Rows[currentRow].Cells[col].Style.WrapMode = DataGridViewTriState.True;
dgv.Rows[currentRow].Height = dgv.Rows[currentRow].Height * mergeCount;
for (int i = 1; i < mergeCount; i++)
{
dgv.Rows[currentRow + i].Cells[col].Visible = false;
}
}
currentRow += mergeCount;
}
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new DataGridViewMergeCells());
}
}
DataGridView控件,并添加了一些示例数据。请注意,这段代码只是一个简单的示例,实际应用中可能需要根据具体需求进行调整和优化。
上一篇:c# 替换字符串
下一篇:c# https
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站