DatagridView如何为每列提供不同的行数?

时间:2017-05-14 12:35:09

标签: c# .net datagridview

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

A B C

1 1 1

2 2 x

3 x x

x表示没有单元格。

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

2 个答案:

答案 0 :(得分:2)

尝试以下

            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;

答案 1 :(得分:1)

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

  

[T]他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;
        }
    }
}

Empty cell's painted like DGV background