Home > Articles > Programming > Windows Programming

This chapter is from the book

Programmatic DataGridView Construction

The most common way of using the grid is with data-bound columns. When you bind to data, the grid creates columns based on the schema or properties of the data items, and generates rows in the grid for each data item found in the bound collection. If the data binding was set up statically using the designer (as has been done in most of the examples in this book), the types and properties of the columns in the grid were set at design time. If the data binding is being done completely dynamically, the AutoGenerateColumns property is true by default, so the column types are determined on the fly based on the type of the bound data items. You may want to create and populate a grid programmatically when working with a grid that contains only unbound data. To know what code you need to write, you need to know the DataGridView object model a little better.

The first thing to realize is that like all .NET controls, a grid on a form is just an instance of a class. That class contains properties and methods that you can use to code against its contained object model. For DataGridView controls, the object model includes two collections—Columns and Rows—which contain the objects that compose the grid. These objects are cells, or more specifically, objects derived from instances of DataGridViewCell. The Columns collection contains instances of DataGridViewColumn objects, and the Rows collection contains instances of DataGridViewRows.

Programmatically Adding Columns to a Grid

There are a number of ways to approach programmatically adding columns and rows to the grid. The first step is to define the columns from which the grid is composed. To define a column, you have to specify a cell template on which the column is based. The cell template will be used by default for the cells in that column whenever a row is added to the grid. Cell templates are instances of a DataGridViewCell derived class. You can use the .NET built-in cell types to present columns as text boxes, buttons, check boxes, combo boxes, hyperlinks, and images. Another built-in cell type renders the column headers in the grid. For each of the cell types, there is a corresponding column type that is designed to contain that cell type. You can construct DataGridViewColumn instances that provide a cell type as a template, but in general you’ll want to create an instance of a derived column type that is designed to contain the specific type of cell you want to work with. Additionally, you can define your own custom cell and column types (discussed later in this chapter).

For now, let’s stick with the most common and simple cell type, a DataGridViewTextBoxCell—a text box cell. This also happens to be the default cell type. You can programmatically add a text box column in one of three ways:

  • Use an overloaded version of the Add method on the Columns collection of the grid:
    // Just specify the column name and header text
    m_Grid.Columns.Add("MyColumnName", "MyColumnHeaderText");
  • Obtain an initialized instance of the DataGridViewTextBoxColumn class. You can achieve this by constructing an instance of the DataGridViewTextBoxCell class and passing it to the constructor for the DataGridViewColumn, or just construct an instance of a DataGridViewTextBoxColumn using the default constructor. Once the column is constructed, add it to the Columns collection of the grid:
    // Do this:
    DataGridViewTextBoxColumn newCol = new DataGridViewTextBoxColumn();
    // Or this:
    DataGridViewTextBoxCell newCell = new DataGridViewTextBoxCell();
    DataGridViewColumn newCol2 = new DataGridViewColumn(newCell);
    // Then add to the columns collection:
    m_Grid.Columns.Add(newCol);
    m_Grid.Columns.Add(newCol2);

    If you add columns this way, their name and header values are null by default. To set these or other properties on the columns, you can access the properties on the column instance before or after adding it to the Columns collection. You could also index into the Columns collection to obtain a reference to a column, and then use that reference to get at any properties you need on the column.

  • Set the grid’s ColumnCount property to some value greater than zero. This approach is mainly used to quickly create a grid that only contains text box cells or to add more text box columns to an existing grid.
    // Constructs five TextBox columns and adds them to the grid
    m_Grid.ColumnCount = 5;

When you set the ColumnCount property like this, the behavior depends on whether there are already any columns in the grid. If there are existing columns and you specify fewer than the current number of columns, the ColumnCount property will remove as many columns from the grid as necessary to create only the number of columns you specify, starting from the rightmost column and moving to the left. This is a little destructive and scary because it lets you delete columns without explicitly saying which columns to eliminate, so I recommend to avoid using the ColumnCount property to remove columns.

However, when adding text box columns, if you specify more columns than the current number of columns, additional text box columns will be added to the right of the existing columns to bring the column count up to the number you specify. This is a compact way to add some columns for dynamic situations.

Programmatically Adding Rows to a Grid

Once you have added columns to the grid, you can programmatically add rows to the grid as well. In most cases, this involves using the Add method of the Rows collection on the grid. When you add a row this way, the row is created with each cell type based on the cell template that was specified for the column when the columns were created. Each cell will have a default value assigned based on the cell type, generally corresponding to an empty cell.

// Add a row
m_Grid.Rows.Add();

Several overloads of the Add method let you add multiple rows in a single call or pass in a row that has already been created. The DataGridView control also supports creating heterogeneous columns, meaning that the column can have cells of different types. To create heterogeneous columns, you have to construct the row first without attaching it to the grid. You then add the cells that you want to the row, and then add the row to the grid. For example, the following code adds a combo box as the first cell in the row, adds some items to the combo box, adds text boxes for the remaining four cells, and then adds the row to the grid.

private void OnAddHeterows(object sender, EventArgs e)
{

   m_Grid.ColumnCount = 5; // Create 5 text box columns
   DataGridViewRow heterow = new DataGridViewRow();
   DataGridViewComboBoxCell comboCell = new
DataGridViewComboBoxCell();
   comboCell.Items.Add("Black");
   comboCell.Items.Add("White");
   comboCell.Value = "White";
   heterow.Cells.Add(comboCell);
   for (int i = 0; i < 4; i++)
   {

      heterow.Cells.Add(new DataGridViewTextBoxCell() );

    }
    m_Grid.Rows.Add(heterow); // this row has a combo in first cell
 }

To add a row to a grid this way, the grid must already have been initialized with the default set of columns that it will hold. Additionally, the number of cells in the row that is added must match that column count. In this code sample, five text box columns are implicitly added by specifying a column count of five, then the first row is added as a heterogeneous row by constructing the cells and adding them to the row before adding the row to the grid.

You can also save yourself some code by using the grid’s existing column definitions to create the default set of cells in a row using the CreateCells method, then replace just the cells that you want to be different from the default:

DataGridViewRow heterow = new DataGridViewRow();
heterow.CreateCells(m_Grid);
heterow.Cells.RemoveAt(0);
heterow.Cells.Insert(0, new DataGridViewComboBoxCell() );
m_Grid.Rows.Add(heterow);

To access the contents of the cells programmatically, you index into the Rows collection on the grid to obtain a reference to the row, and then index into the Cells collection on the row to access the cell object.

Once you have a reference to the cell, you can do anything with that cell that the actual cell type supports. If you want to access specific properties or methods exposed by the cell type, you have to cast the reference to the actual cell type. To change a cell’s contents, you set the Value property to an appropriate value based on the type of the cell. What constitutes an appropriate value depends on what kind of cell it is. For text box, link, button, and header cell types, the process is very similar to what was described for the Binding object in Chapter 4. Basically, the value you set on the Value property of the cell needs to be convertible to a string, and formatting will be applied in the painting process. To change the formatting of the output string, set the Format property of the style used for the cell. The style is an instance of a DataGridViewCellStyle object and is exposed as another property on the cell, not surprisingly named Style. The cell’s style contains other interesting properties that you can set (described later in the section “Formatting with Styles”).

For example, if you want to set the contents of a text box cell to the current date using the short date format, you could use the following code:

m_Grid.Rows[0].Cells[2].Value = DateTime.Now;
m_Grid.Rows[0].Cells[2].Style.Format = "d";

This sets the value of the third cell in the first row to an instance of a DateTime object, which is convertible to a string, and sets the format string to the short date predefined format string “d” (which is the short date format—MM/YYYY). When that cell gets rendered, it will convert the stored DateTime value to a string using the format string.

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