ghulam_ali
ghulam_ali

Reputation: 295

Re sizing DataGridView according to its content

I was looking to re size DataGridView according to its content. Because data source of grid view may have different size depending upon the data in it.I found resizing DataGridview according to Form size, but no way to re size DataGridView according to its content. Any one have some idea? enter image description here

Upvotes: 0

Views: 416

Answers (1)

ainla
ainla

Reputation: 529

First use Anchor property to anchor your form elements to form borders. I made a example form to illustrate it. There is a groupBox with some random controls and dataGridView with a many columns:

Example form with DataGridView and some random controls

Here are the Anchor setting for the form elements:

enter image description here

Now, when i load the form, I calculate the total width of dataGridView columns and increase the from width accordingly:

    private void Form1_Load(object sender, EventArgs e)
    {
        int totalWidth = 0;
        foreach (DataGridViewColumn col in dataGridView1.Columns)
            totalWidth += col.Width;

        //assign Form1.width (add 100 extra pixels for borders etc.)
        this.Width = totalWidth + groupBox1.Width + 100;
    }

Upvotes: 2

Related Questions