(* note when running this application, you may need to add the reference to the Microsoft Excel 11.0 Object Library)

Figure 1 - GridView Control Sized to fit Columns and Rows
Introduction
This article is in response to the forum question: How do I size the gridview control.Unfortunately the grid view control does not work well once scrolling is necessary.Therefore I've added the method SizeToFitAll() which sizes the GridView to fit the exact number of rows and columns set in the NumberOfRows and NumberOfColumns properties of the GridView.Therefore you can use the GridView when scrolling will not be necessary.Also added to the GridView in this article is the ability to use the tab key to tab forward through the grid like in an excel spreadsheet.Tabbing is accomplished using the override to ProcessCmdKey.
Coding to Fit the Grid
The GridView was sized by breaking down the methods into SizeToFitRows and SizeToFitColumns. These methods simply call set bounds on the GridView control to make all the rows and columns visible respectively. Both methods use the SetBounds method of the control. The methods call CalculateHeight and CalculateWidth in order to determine the width and height of the total columns and total rows.
int CalculateHeight()
{
if (NumberOfRows == 0)
return 0; // precondition
// calculate height based on the number of rows and the height of an item in the row
int height = (this.NumberOfRows + 2) * listView1.Items[this.NumberOfRows -]
.Bounds.Height;
return height-5;
}
int CalculateWidth()
{
if (NumColumns == 0)
return 0; // precondition
//width is based on the sum of all the column widths
int width = SumColumnWidths();
return width + 5;
}
public void SizeToFitRows()
{
// set the bounds of the grid based on the total height of the rows
SetBounds(this.Left, this.Top, this.Width, CalculateHeight());
}
public void SizeToFitColumns()
{
// set the bounds of the grid based on the total width of the columns
SetBounds(this.Left, this.Top, CalculateWidth(), this.Height);
}
public void SizeToFitAll()
{
SizeToFitRows();
SizeToFitColumns();
}
Processing the Tab

Join the conversation! Your thoughts help the community grow.