Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Using the Built-In Column Types

Using a text box column is straightforward enough: you data bind to something that can be rendered as text, or set the Value property on a cell to something that can be converted to a string, and you are done. Using some of the other cell types may not be as easy to figure out, so this section steps through each of the built-in column types, pointing out its capabilities and how to use it.

The first thing to realize is that even though most of the functionality is surfaced at the cell level in a DataGridView and it can support spreadsheet-like behavior (as described later in this chapter), the grid is still primarily a tabular control. The columns in the grid usually represent information that can be determined at design time—specifically, the schema of the data that will be presented. The rows are usually determined dynamically at runtime and map to the structure specified by the columns. You may occasionally programmatically create columns for rendering based on dynamic data schemas at runtime, but even then you are first defining the data’s shape (the columns) and then providing the data (the rows).

As a result, for each of the built-in cell types that the grid is capable of displaying, there is a corresponding column type designed to contain cells of that type. Each cell type is derived from the DataGridViewCell class, and each of the corresponding column types is derived from DataGridViewColumn. Each of the column types expose properties to aid in the data’s data binding, and each column type corresponds to the expected content for the type of cells that the column contains. Likewise, each derived cell type may expose additional properties based on the type of content it is designed to display.

Because each built-in column type is different in subtle ways, it’s best to cover them one at a time. However, since all of the cell types contained by the column types derive from the same base class, there are a number of properties from the base class that you’ll use for controlling and accessing cell content. The properties of the DataGridViewCell base class are described in Table 6.1.

DataGridViewCell Properties

View Table

The DataGridViewColumn (discussed earlier in this chapter) is the base class from which built-in column types derive. This class also has a number of useful properties that you can set to drive the behavior of the grid and that the type-specific column classes inherit. These properties are described in Table 6.2.

DataGridViewColumn Properties

View Table

There are a number of built-in column types that are available for using with the DataGridView control corresponding to the most common control types that developers want to include in a grid. The following subsections describe each of the built-in column types and what is involved in using them.

DataGridViewTextBoxColumn

This is the default type of column (as described earlier in this chapter), and it displays text within the contained cells, which are of type DataGridViewTextBoxCell. Data that is bound to this column type and values set on the cell have to be of a type that can be converted to a string.

This column type supports editing if the ReadOnly property is true (the default) and the focus in on the cell. To enter editing mode, press F2, type in characters, or click in the cell. This embeds a separate editing control of type DataGridViewTextBoxEditingControl, which derives from TextBox. This type enables in-place editing for the grid value, like you are used to for text box controls. The value in the text box is treated as a transient value until the focus leaves the cell; then the CellParsing event fires, and the value is pushed into the underlying data store if data bound or the CellValuePushed event fires if in virtual mode.

DataGridViewButtonColumn

This column type displays cells of type DataGridViewButtonCell, which is sort of a fancy form of read-only text cell. A button cell lets you have a button-push experience embedded in the grid, which you can use to trigger whatever action makes sense for your application. The button cell renders itself with a border that looks like any other button control, and when the user clicks on it, the cell renders again with a depressed offset so that you get an action like a button. To handle the “button click,” you need to handle the CellClick event on the grid, determine if it was a button cell that was clicked, and then take the appropriate action for your application. This involves taking the event argument from the CellClick event, checking its ColumnIndex property against the column index of button columns in your grid, and then calling the button click handling code from there based on the row index, or the contents of that cell or others in that row.

DataGridViewLinkColumn

Like the button column, this is another form of rendering a text cell that gives the user a visual cue that clicking on it will invoke some action. This column type contains cells of type DataGridViewLinkCell and renders the text in the cell to look like a hyperlink. Typically, clicking on a link “navigates” the user somewhere else, so you might use this kind of column if you are going to pop up another window or modify the contents of another control based on the user clicking on the link. To do so, you handle the CellClick event as described previously for the button, determine if you are in a cell containing a link, and take the appropriate action based on that link. You will have to derive the context of what action you should take either from the cell’s contents or other cells in that row or column.

DataGridViewCheckBoxColumn

By now you are probably picking up the pattern, and as you would guess, this column type contains cells of type DataGridViewCheckBoxCell. This cell type renders a CheckBox-like control that supports tri-state rendering like a CheckBox control.

The values that this cell type supports depend on whether you set the cell or column type into ThreeState mode or not. If the ThreeState property is set to false (the default), then a value of null or false will leave the check box unchecked; a value of true will check the box. If ThreeState is set to true, then the Value property of the cell can be null or one of the CheckState enumeration values. If null and ThreeState is true, then the check box will be rendered in the indeterminate state (a square filling it). The CheckState enumeration values are Unchecked, Checked, and Indeterminate, which are self-explanatory. The cell’s Value property can be set explicitly through programmatic code that accesses the cell in the Cells collection of the row, or it can be set through data binding.

DataGridViewImageColumn

This column, not surprisingly, contains cells of type DataGridViewImageCell, which support the rendering of images directly within the grid’s cells. This cell type provides a very handy and easy-to-use capability in the DataGridView control that used to be fairly painful to achieve with the DataGrid control. This column type exposes Image and ImageLayout properties in addition to the usual base class properties. Setting the column’s Image property results in that image being displayed by default for all the cells in that column. The ImageLayout property takes a DataGridViewImageCellLayout enumeration value. The values of this enumeration and their effect on the rendering of an image in the grid are described in Table 6.3.

DataGridViewImageCellLayout Enumeration Values and Effects

Value

Effect

NotSet

This is the default and indicates that the layout behavior has not been explicitly specified. The resulting behavior of the cell is the same as if Normal had been explicitly set.

Normal

The image is rendered at its native size and centered in the cell. Depending on the size of the cell, any portions of the image that are outside the bounds of the cell will be clipped.

Stretch

The image is stretched or shrunk in both width and height so that it fills the cell and no clipping occurs. No attempt is made to maintain the aspect ratio (width/height) of the image.

Zoom

The image is resized so that it fits within the cell without clipping, and the aspect ratio (width/height) is maintained so that no distortion of the image occurs.

In addition to setting a default image at the column level, you can set the Value property at the cell level, either explicitly through code or implicitly through data binding. The value can be set to any type that can be converted to an Image object for display in the cell. Natively in .NET, this means that the value can either be an Image or a byte array that contains a serialized Image.

DataGridViewComboBoxColumn

This column type contains cells of type DataGridViewComboBoxCell, which renders itself like a standard ComboBox control within the cell. This column type is definitely the most complex built-in column type for the DataGridView, and it exposes a number of properties that drive its behavior, as described in Table 6.4.

DataGridViewComboBoxColumn Properties

View Table

The combo box cells support edit mode, and users can type in a value for autocompletion purposes or select values from a drop-down list. When in edit mode, this cell type hosts a control that derives from the ComboBox control, so all of its functionality is exposed when the cell is switched into edit mode.

The Value property represents the currently selected value in the combo box. It may contain the displayed text value in the combo box, or it may contain the underlying ValueMember value for the selected item, depending on what you set for the DataSource, DisplayMember, and ValueMember properties. The FormattedValue property, inherited from the base class, always contains the formatted text for the selected item that is being displayed in the combo box.

Data binding this column type or the cells in it works just like data binding a standalone ComboBox control. You set the DataSource, DisplayMember, and ValueMember properties, and the items in the data source collection are rendered in the drop-down list using the value of the data member that is identified as the display member:

toCountryColumn.DataSource = m_CountriesBindingSource;
toCountryColumn.DisplayMember = "CountryName";
toCountryColumn.ValueMember = "CountryID";

The sample code that accompanies this chapter contains a simple application called ColumnTypes that demonstrates how the code interacts with each of the built-in column types described in this chapter.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020