Apple
Apple

Reputation: 17

DatagridView How to have a different row count per column?

So I was trying to display my data in specific format in a datagridview. So my format goes like this:

A B C

1 1 1

2 2 x

3 x x

the x means no cell.

As you can see each column has different row count. I want to achieve the same result in DatagridView or in any other control in the Dot Net Framework.

Upvotes: 0

Views: 1043

Answers (2)

OhBeWise
OhBeWise

Reputation: 5454

To expand on jdweng's answer, if for some reason you truly want:

[T]he x means no cell.

Then you can handle the DataGridView.CellPainting event to effectively hide the empty cell. Mind you, it will start to look odd when null cells are intermingled amidst valued cells - and not just at the row ends.

// ...
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

Upvotes: 1

jdweng
jdweng

Reputation: 34433

Try following

            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;

Upvotes: 2

Related Questions