Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize DataGridView width to fit Columns

I have a DataGridView that is filled programmatically. The columns are set to auto-resize according to cell content.

The DataGridView will be populated with parts information regarding hydraulic and pneumatic schematics. My form only has a SplitContainer, a PictureBox and the DataGridView. The SplitterDistance is linked to the width of the DataGridView.

The DataGridView will only have a maximum of 6 columns ("Index", "Part Number", "Serial Number", "Drawing Number", "Page Number", "Revision Number") and a minimum of 2 columns depending on the schematics requirements. So I want to resize the control accordingly.

How can I get the DataGridView control to resize to the total width of the columns so that the scrollbar doesn't show?

like image 613
Jared6243 Avatar asked Jan 11 '23 14:01

Jared6243


2 Answers

Execute the following code after the grid is loaded with data and the columns have been sized accordingly (assuming you're setting the columns' AutoSize property at runtime).

dataGridView1.Width =
    dataGridView1.Columns.Cast<DataGridViewColumn>().Sum(x => x.Width)
    + (dataGridView1.RowHeadersVisible ? dataGridView1.RowHeadersWidth : 0) + 3;

What it's doing:

  • Totals up the widths of all columns (using LINQ),
  • Sees if the "row header" is visible and adds that width too, if it is,
  • Adds 3 more because without that the horizontal scrollbar kept showing up - possibly because of margin/padding around the grid, I'm not sure.
like image 140
Grant Winney Avatar answered Jan 24 '23 10:01

Grant Winney


ok so to clarify what you want (And answer it)

I suppose you want to make DataGridView width expand in size so no horizontal scroll bar ever appears? (btw while you are at it you can increase the form containing it too)

For example, right now I have

enter image description here

There is a column 1, 2 and 3 there.

i'd want the datagridview to expand to a size that fits all the columns

enter image description here

And let's say more data is added

I can do these two lines to expand the cells,

dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; 
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

but I still get a horizontal scroll bar, because the size of the datagridview has not changed. even though the size of each column has.

enter image description here

I can see that there is a datagridview1.Size property, and a dataGridView1.Width property. Either can be used.

Also notice that there is a funny kind of column before the first column.

So if you did make the dataGridView1.Width equal to the size of cols 1,2,3 you'd still have a scroll bar, because of that funny column like thing to the left of the column labelled "column 1". I see it has a width of 50 units. So if you make the dataGridView1.Width = 50 plus the width of each column, then that grey dataGridView area, will always be big enough to include all the columns.

I draw a datagridview and a textbox, the textbox shows the size of the datagridview.Width and the total width of all the columns, and the width of each individual column.

this works for me.

So the columns are set to expand in size or decrease in size according to the amount of content in them, but not only that.. DataGridView.Width will increase, by 50(the funny column on the far left), plus the size of all the regular/rest of the columns.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace automaticallyexpanddatagridviewsizeandformsize
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
          //  MessageBox.Show(dataGridView1.Size.Width.ToString());

            // note that with these two set you can't change the width of a column
            // also  MininimumWidth would limit changing the width of a column too, 
            //http://stackoverflow.com/questions/2154154/datagridview-how-to-set-column-width
            // but that doesn't matter because we aren't programmatically changing the width of any column.

            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; 
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;




        }



        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

            int olddgvsize = dataGridView1.Width;

            textBox1.Text = dataGridView1.Columns[0].Width.ToString();
            int h=dataGridView1.Height;

            int tw = 0;
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
              //  MessageBox.Show(dataGridView1.Columns[i].Width.ToString());
                tw += dataGridView1.Columns[i].Width;

            }
            tw += 50; // column before col 0..

           //you only need one of these.
           //though to better understand the code you can try to comment out both and see how the total width of all columns (tw)(+50) so ALL the columns, differs from  the DataGridView.Width (the total area which includes all columns plus some grey if it's much bigger than all the columns)

            dataGridView1.Size = new Size(tw, h);
            dataGridView1.Width = tw;

                textBox1.Text = "tw=" + tw + " " + "dgvw=" + " " +dataGridView1.Width+ "  "+"col 1:" + dataGridView1.Columns[0].Width + " col 2:"  + dataGridView1.Columns[1].Width + " col 3:"+ dataGridView1.Columns[2].Width;

                int newdgvsize = dataGridView1.Width;
                int differenceinsizeofdgv = newdgvsize - olddgvsize;
                this.Width = this.Width + differenceinsizeofdgv;


        }


    }



}

So for example I have

tw is the total width of all the columns (ALL the columns so including the weird column to the left of column 1, which i've considered to be as 50 in width, maybe it is)

dgvw is dataGridView.Width

enter image description here

And thanks to the code above, dgvw expands with tw.

enter image description here

And the code above also expands the form by the amount that the dataGridView expanded.

like image 24
barlop Avatar answered Jan 24 '23 11:01

barlop