(* note when running this application, you may need to add the reference to the MicrosoftExcel 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 rowint 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 widthsint width = SumColumnWidths();return width + 5;}publicvoid SizeToFitRows(){// set the bounds of the grid based on the total height of the rowsSetBounds(this.Left, this.Top, this.Width, CalculateHeight());}publicvoid SizeToFitColumns(){// set the bounds of the grid based on the total width of the columnsSetBounds(this.Left, this.Top, CalculateWidth(), this.Height);}publicvoid SizeToFitAll(){SizeToFitRows();SizeToFitColumns();}Processing the Tab

It took me a bit to figure out how to capture the tab key in code because the tab key is a command key so it will not necessarily be trapped in the event handlers for KeyPress or KeyDown. I thought maybe I had to capture the tab in the WndProc but this proved fruitless as well. It turns out that the tab key event is trapped in an override called ProcessCmdKey. This method actually gets called when you press the tab key when inside an edit box. The code for trapping the tab key press and tabbing the edit field in the GridView is shown below. Note you can also test for modifier keys such as CTRL and ALT by OR'ing the keyData with the command key in question.

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE ... Read more