Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Auto Resize Form to DataGridView's size

I have a Form and a DataGridView. I populate the DataGridView at runtime, so I want to know how do I resize the Form dynamically according to the size of the DataGridView? Is there any sort of property or method? Or do I have to determine the size myself and update accordingly?

like image 455
akif Avatar asked Oct 22 '09 14:10

akif


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

You can find the actual width by count Columns width.

Don't forget that your form may be more complex and your should count other controls.

public class YourForm : Form
{
    public YourForm()
    {
        DataGridView _dgv = new DataGridView() { Dock = DockStyle.Fill};
        Controls.Add(_dgv);
    }
    public void CorrectWindowSize()
    {
        int width = WinObjFunctions.CountGridWidth(_dgv);
        ClientSize = new Size(width, ClientSize.Height);
    }
    DataGridView _dgv;
}

public static class WinObjFunctions
{
    public static int CountGridWidth(DataGridView dgv)
    {
        int width = 0;
        foreach (DataGridViewColumn column in dgv.Columns)
            if (column.Visible == true)
                width += column.Width;
        return width += 20;
    }
}
like image 111
Artur A Avatar answered Oct 11 '22 01:10

Artur A


int dgv_width = dataGridView1.Columns.GetColumnsWidth(DataGridViewElementStates.Visible);
int dgv_height = dataGridView1.Rows.GetRowsHeight(DataGridViewElementStates.Visible);
this.Width = dgv_width;
this.Height = dgv_height;

this.Width resizes this Form width.

Of course you've to add fixed values (for example margin, Form title heigth, ecc.). With tests i've reached the values working for me (don't ask why...):

this.Width = dgv_width + 147;
this.Height = dgv_height + 47;
like image 42
T30 Avatar answered Oct 11 '22 01:10

T30