很遗憾,您不能在 DataGridView 中执行此操作。但是,您可以创建一个如下所示的表:
GROUP USER
------ -----
Group1 User1
Group1 User2
Group1 User3
Group2 UserA
Group2 UserB
完成此操作后,您可以处理 DataGridView 的 CellFormatting 事件,如果上面单元格的值匹配,则将 e.FormattedValue 设置为 String.Empty。然后你的桌子会“看起来”像:
GROUP USER
------ -----
Group1 User1
User2
User3
Group2 UserA
UserB
这几乎就是您想要的。如果您希望网格线消失,您可以改为处理 DataGridView 的 CellPainting 事件以绘制正确的边框、居中文本等。
更新:这是使用 CellFormatting 事件隐藏单元格内容的示例。在这个例子中,我只是使用一个 List 作为我的数据源,但是你可以用它来代替你的 SQL 数据源、DataTable 等。
public partial class Form1 : Form
{
private List<GroupUserRow> _rows = new List<GroupUserRow>();
public Form1()
{
InitializeComponent();
_rows.Add(new GroupUserRow { Group = "Group1", User = "User1" });
_rows.Add(new GroupUserRow { Group = "Group1", User = "User2" });
_rows.Add(new GroupUserRow { Group = "Group1", User = "User3" });
_rows.Add(new GroupUserRow { Group = "Group2", User = "UserA" });
_rows.Add(new GroupUserRow { Group = "Group2", User = "UserB" });
dataGridView1.DataSource = _rows;
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == 0)
{
int prevRowIndex = e.RowIndex - 1;
if (prevRowIndex >= 0 && dataGridView1[0, prevRowIndex].Value == e.Value)
{
//this just "hides" the value from the screen, the value is not
//removed from the cell
e.Value = String.Empty;
e.FormattingApplied = true;
}
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
MessageBox.Show("This cell's value is: " + dataGridView1[e.ColumnIndex, e.RowIndex].Value);
}
}
}
public class GroupUserRow
{
public string Group { get; set; }
public string User { get; set; }
}