The .NET Newbie’s Guide to Customizing the DataGridView Control

The .NET Newbie’s Guide to Customizing the DataGridView Control

hen creating a connection to foreign data, the .NET configuration wizard is a great place to start. Not only will it create a point-and-click connection for you, but it also can quickly and easily produce a control for users to retrieve, display, and manipulate the data. However, the wizard seldom will produce a control that provides the exact functionality your users need. You can expect to tweak the wizard’s control offerings a bit?sometimes quite a bit?to add the required functionality.

This article walks the .NET novice coming from Access or SQL Server through building a basic connection and then customizing the resulting control. Using the Visual Basic Express (VB Express) configuration wizard, the article demonstrates how to populate a DataGridView control and then enhance it to do the following:

  • Display alternate row colors to create a greenbar affect.
  • Disable the DataGridView’s built-in sorting capability for a single column.
  • Show the edit row when executing the form.

Getting Started

VB Express offers a number of ways to retrieve and manipulate foreign data. For someone learning .NET, it’s often best to let VB Express do as much of the work as possible. For instance, by simply running its configuration wizard, you can have VB Express establish a connection to the Customers table in the MS Access sample database, Northwind.mdb:

  1. Launch VB Express and click New Project on the Standard toolbar to start a new project. Click Windows Form Application in the resulting dialog box.
  2. Enter a meaningful name in the Name control, and click OK.
  3. Click the Data Sources tab (bottom right) in Solution Explorer. If the tab isn’t available, choose Show Data Source from the Data menu.
  4. Click Add New Data Source to launch the Data Source Configuration Wizard.
  5. Click Next, as the Database option is the default.
  6. Click New Connection in the next pane.
  7. In the resulting Add Connection dialog box, click Change and choose Microsoft Access Database File from the Change Data Source dialog box, and click OK.
  8. Click Browse in the Add Connection dialog box, locate Northwind.mdb (in the Samples folder of your Office directory), and click OK.
  9. Click Test Connection and then click OK to clear the confirmation message.
  10. With the connection working, click OK to return to the wizard, and click Next to continue.
  11. At this point, the wizard needs you to identify specific data.

  12. VB Express asks you if you want to copy the database. If you click Yes, it will copy the entire database into your project. For this example, click No.
  13. The next pane lets you save the connection string in the configuration file. The default is Yes, and most of the time this is the best choice. Click Next.
  14. Figure 1. The Form and Grid in Form Design: Let the Configuration Wizard build a control that can display data.

    The wizard will retrieve the data objects in the connected database and display them in the source file. This is where you identify the data you want to retrieve and manipulate in your .NET project.

  15. Click the plus sign (+) to expand the Tables node, and check the Customers table. Retain the default name, NorthwindDataSet, that VB Express supplies for the dataset.
  16. Click Finish, and VB Express will retrieve the specified data.

After creating the connection, you’ll need a form to display that data, so do the following:

  1. Click the Data Sources tab.
  2. Click the Form1 tab (if necessary) and drag the Customers dataset from the Data Sources tab to Form1 in Form Designer. VB Express will generate a DataGridView control and name it accordingly, using the selected item’s name. Figure 1 shows the resulting form and grid in Form Design.
  3. Choose Save All from the File menu and then click Save.

You now have a dataset filled with customer data from Northwind and a form that displays that data in a DataGridView control. And all you did was run a wizard!

Enhancement One: Alternate Row Colors

The first enhancement you will make to the control that the wizard produced is to improve readability by alternating the row colors. With the DataGridView, it’s as easy as changing a property:

  1. In Form Design, select the DataGridView control. (Don’t double-click, as that will open the form’s code page.)
  2. In the Properties window, open the AlternatingRowsDefaultCellStyle properties.
  3. Click the BackColor property’s dropdown arrow to display the CellStyleBuilder dialog box.
  4. Choose a color other than the current color (white by default). For this example, select blue (as shown in Figure 2) and then click OK.
  5. Press F5 to run the application. Figure 3 shows the populated grid control using alternating row colors.

Figure 2. CellStyleBuilder Dialog Box: Select an alternating row color.
Figure 3. The Populated Grid Control: The control alternates blue and white row colors.

Remember, the property sets alternating row properties, not all row properties. If you want more variety, set the BackColor and ForeColor properties accordingly.

Enhancement Two: Controlling Sort Order

Initially, the control you produced populated by table order because it had no specified sort order. However, sorting is native to the DataGridView. Simply click a header cell and the control will sort the records by that column in ascending order. A second click will sort the records in descending order. For a bit more control, you can sort the data when populating the control:

  1. In Form Design, select the CustomersBindingSource component just below the form. Selecting it will update the items in the Properties window accordingly.
  2. Find Sort (at the very bottom) and enter City, as shown in Figure 4.
  3. Press F5 to run the application. As you can see in Figure 5, the control sorts the records by the City values in ascending order. For a descending sort, simply include the DESC keyword. For example, to sort by the City values in descending order, you’d enter City DESC, instead of just City.

Figure 4. Find Sort and Enter City: Specify a sort column.
Figure 5. The Control Sorts the Records: The form sorts the records by the City values.

You may choose to inhibit this native sort capability. You can do so with just a bit of code, but you must add a statement to the form’s class for each column that you want to disable. For instance, to inhibit the sort capability for the Contact Title column, do the following:

Figure 6. Clicking the Builder Button: Click the Builder button to view the grid’s Columns collection.
  1. With the form in Design view, choose Code from the View menu, or press F7.
  2. Start typing the statement. You’ll quickly find that IntelliSense doesn’t display the control’s underlying columns by name. Instead, it presents a list of columns identified by position, which isn’t the best way to reference columns.
  3. To change the default name of a DataGridView control’s columns, you must change the Columns collection for the control itself. In Design view, double-click the grid (not the form). You might have to enlarge the form just a bit to select only the grid. Doing so will update the properties. When the properties title displays CustomersDataGridView, you know you’ve selected the grid and not the form.
  4. Locate the Columns collection and click the Builder button shown in Figure 6 to launch the Edit Columns dialog box.
  5. In the Select Columns control, select ContactTitle.
  6. In the Design section (bottom right), the Name property for this control is DataGridViewTextBoxColumn4. Simply replace it with a more meaningful name. In this case, DataGridViewTextBoxContactTitle, as shown in Figure 7. Although you won’t do so right now, this is where you would render invisible columns that you don’t need by setting the Visible property to False.
  7. Click OK and return to the code window (Form1.vb).
  8. Enter the following statement:
    Me.DataGridViewTextBoxContactTitle.SortMode = DataGridViewColumnSortMode.NotSortable

    This time, IntelliSense lists the column by name, instead of position (see Figure 8).

  9. Save the changes you just made by clicking Save Form1.vb in the Standard menu.
  10. Press F5 to execute the project. In the resulting form, click ContactTitle’s header cell. This time, the form won’t sort the records. That’s because the statement you entered disabled that feature for that column.

  11. Figure 7. A Meaningful Name for the Name Property: Enter a meaningful name for the column.
    Figure 8. IntelliSense Lists the Column by Name: Using a column name instead of a position number is self-documenting.

    Enhancement Three: Display Edit Row

    Currently, the example form displays 91 records. As is, users wanting to enter a new record must scroll through all the records to access the edit row. As an enhancement, you could program the form to display the edit row automatically. Add the following statement to the form’s Load event, as shown in Figure 9:

    Me.CustomersDataGridView.FirstDisplayedScrollingRowIndex = CustomersDataGridView.Rows.Count - 1
    Figure 9. Added Statement in the Form’s Load Event: Force the form to show the edit row when loaded.

    Press F5 to run the form. As you can see in Figure 10, the form displays a few records and the edit row. The statement subtracts one from the row count, which prevents an exception because the edit row doesn’t actually have an index until you click in it, even though it affects the row count. Contrary to what you might think, this process just makes sure that the last row is visible. All of the records are still available through scrolling. The number of existing records the form displays depends on how many it can accommodate (by size). The statement doesn’t have anything to do with the number of existing records the form displays.

    By disabling the edit row, you could just as easily turn this form into a simple browsing form that doesn’t accept new records. Simply add the following statement to the form’s Load event:

    DataGridView1.AllowUserToAddRows = False
    Figure 10. Form Displaying Records and Edit Row: Now when you launch the form, it displays the edit row.

    Set the AllowUserToAddRows property to True to enable the edit row.

    Customized Native Controls for Ease and Flexibility

    It took very little time to customize the example form:

    • Alternating row color required a simple property change.
    • Inhibiting the built-in sort required one row of code.
    • Displaying the edit row required one row of code.

    If you’re coming from Access or SQL Server, you can certainly appreciate the elegance and ease with which you can create and implement a form for browsing or editing data.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist