【问题标题】:DatagridView How to have a different row count per column?DatagridView 如何每列有不同的行数?
【发布时间】:2023-03-21 09:14:02
【问题描述】:

所以我试图在datagridview 中以特定格式显示我的数据。 所以我的格式是这样的:

A B C

1 1 1

2 2 x

3 x x

x 表示没有单元格。

如您所见,每一列都有不同的行数。我想在 DatagridView 或 Dot Net Framework 中的任何其他控件中实现相同的结果。

【问题讨论】:

  • 这是不可能的,因为 DGV 将始终保存一个二维数组。当然,填充哪些单元格取决于您。 - 您可以在列表视图中为每个项目设置不同的列数,因为它的项目是锯齿状数组。因此显示的效果是可能的,但仅与每行末尾缺失的单元格一样 lonf。

标签: c# .net datagridview


【解决方案1】:

尝试关注

            DataTable dt = new DataTable("MyDataTable");

            dt.Columns.Add("A", typeof(int));
            dt.Columns.Add("B", typeof(int));
            dt.Columns.Add("C", typeof(int));

            dt.Columns["A"].AllowDBNull = true;
            dt.Columns["B"].AllowDBNull = true;
            dt.Columns["C"].AllowDBNull = true;

            dt.Rows.Add(new object[] { 1,2,3});
            dt.Rows.Add(new object[] { 2, 2, });
            dt.Rows.Add(new object[] { 3 });

            datagridview1.DataSource = dt;

【讨论】:

  • 感谢我正在寻找的东西
【解决方案2】:

扩展jdweng's answer,如果出于某种原因你真的想要:

[T]he x 表示没有单元格。

然后您可以处理DataGridView.CellPainting 事件以有效隐藏空单元格。请注意,当null 单元格混合在有价值的单元格中时,它会开始看起来奇怪 - 而不仅仅是在行尾。

// ...
dt.Rows.Add(new object[] { 3, null, null });

this.dataGridView1.DataSource = dt;
this.dataGridView1.CellPainting += DataGridView1_CellPainting;

private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
    {
        DataGridViewCell cell = this.dataGridView1[e.ColumnIndex, e.RowIndex];

        if (cell.Value == null || cell.Value is DBNull)
        {
            using (SolidBrush brush = new SolidBrush(this.dataGridView1.BackgroundColor))
            {
                e.Graphics.FillRectangle(brush, e.CellBounds);
            }

            e.Handled = true;
        }
    }
}

【讨论】:

  • 哇,这真的是答案
猜你喜欢
  • 2015-01-27
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多