Developers have come up with various ways to implement features for changing data displayed in grid controls or to add new data rows. Such methods include devising special data entry screens or displaying text box controls that allow data modification. In this article, we’ll look at a simple way of entering and updating data in the grid control itself. In our example, we will use a regular Microsoft Flex Grid control.
First, create a simple VB project by following these steps:
- · Fire up VB and start a new project.
- · Go to Project Components and check Microsoft FlexGrid Control 6.0.
- · Add an MS FlexGrid control to your form and call it grdInfo. Your screen should resemble Figure A.
- · Add the following code to the Form Load event:
- · Call SetGridProperties
- · Add the code in Listing A to the grdInfo_KeyPress(KeyAscii As Integer) event.
- · Add Private Sub SetGridProperties() using the code in Listing B.
- · Add Private Sub FillData() using the code in Listing C.
- · Press [Ctrl][F5] to run the project, and you should see a screen that resembles Figure B.
Now, click on the first cell of the first row, press [Backspace] a few times to get rid of the text that’s already there, and type in something else. As you’ll see, you can modify the contents of the cells.
How does it work?
On the Form Load event, we call two subs: SetGridProperties and FillData. SetGridProperties sets the properties of the grid control, specifying the number of rows and columns and setting the column headers and the state of the selection mode. In FillData, we add data to the grid and move the selection to the first data column of the first row.
In grdInfo_KeyPress, the whole action takes place. When a user starts typing into the grid, this event is called. KeyAscii is the code of the key the user presses. We check which key was pressed and, based on that key, take some action. We use Select Case to decide what needs to be done.
KeyAscii codes 65 to 90, 97 to 122, and 48 to 57 represent lowercase letters (a–z), uppercase letters (A–Z), and numbers (0–9). If one of those is pressed, we want to add data to the selected grid’s cell. We do that using the Text property of the grid, which returns the current text of the selected cell and adds the appropriate character to it.
KeyAscii code 8 represents a backspace. If the [Backspace] key is pressed, we want to remove one letter from the text in the selected cell. Again, we use the Text property of the grid to do this. First, we set the Text property to its original value (the text contained in the cell). Then, we use the Left function to return the characters in that text, minus the last one. You can see the code in its entirety here.