Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust DataGridView's columns to fill available space if the grid is smaller and use scroll in case the grid bigger than the space available

I want to adjust all columns of a DataGridView according to the required space to show all its data completely. If the space required is smaller than the available space i want the grid to fill this exceeding space, but if the available is space is not enough to display properly all columns i want to DataGridView create automatically a scroll. Is there an easy way to do this?

like image 297
joaocarlospf Avatar asked Jan 26 '12 20:01

joaocarlospf


2 Answers

Click over the DataGridView and select "Edit Columns...", then go to "Layout" and set "AutoSizeMode" to "Fill".

Hope this is what you're looking for.

Cheers

like image 62
joaopintocruz Avatar answered Oct 14 '22 12:10

joaopintocruz


If you want to keep your table (DataGridView) formatted such that all of the columns are automatically sized, but one column in particular fills the remaining space, you can do something like this:

//Store the number of columns in a variable
int columnCount = dataGridView.Columns.Count;

//If we want the last column to fill the remaining space
int lastColumnIndex = columnCount - 1;

//Loop through each column and set the DataGridViewAutoSizeColumnMode
//In this case, if we will set the size of all columns automatically, but have
//the last column fill any extra space available.
foreach(DataGridViewColumn column in dataGridView.Columns) 
{
    if (column.Index == columnCount - lastColumnIndex) //Last column will fill extra space
    {
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
    }
    else //Any other column will be sized based on the max content size
    {
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    }
}

//Turn the scrollbars on for the DataGridView if needed
dataGridView.ScrollBars = ScrollBars.Both;
like image 39
the_cwazy_wabbit Avatar answered Oct 14 '22 14:10

the_cwazy_wabbit