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.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists