Home

Windows Control: The Data Grid View

 

Data Grid View Fundamentals

 

Introduction

Like a list view, a data grid view is a rectangular control made of columns and rows:

The Data Grid View

The top section of the control displays column headers as gray boxes with each showing a caption. On the left side, there are gray boxes referred to as row headers. The cells are the intersections of the columns and the rows. Those cells are white. These are the default characteristics of columns, rows, and cells. In reality, most aspects can be customized. They can show different colors, different widths, and different heights.

To use the data grid view, the user can identify a column, click a cell under it, and start typing. By default, each cell behaves like a text box. The user can:

  • Click into it to create a new entry
  • Edit the content of a cell
  • Right-click a cell to display the default context-sensitive menu of a text box as defined in the Microsoft Windows operating system

As mentioned already, by default, the cells of a data grid view are made of text boxes. If you want, you can make the cells under a column appear as combo boxes, check boxes, buttons, links, or pictures:

Data Grid View

Remember that many aspects of  a data grid view can be customized. For example, you can let the user change the width of a column. You can display a context menu when the user right-clicks a column header or a row header. You can display a context menu when the user right-clicks any cell of the data grid view.

Creating a Data Grid View

To support the data grid view, the Toolbox of Microsoft Visual Studio is equipped with the DataGridView button DataGridView. Therefore, to get a data grid view, in the Data section of the Toolbox, you can click the DataGridView button DataGridView and click the form of your application. This would create a gray rectangular box with black borders:

Data Grid View

To support the data grid view, the .NET Framework provides a class named DataGridView. Therefore, to programmatically create a data grid view, declare a variable of type DataGridView and add it to the Controls collection of the form. Here is an example:

Public Class Exercise
    Private dgvStudents As DataGridView

    Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
        dgvStudents = New DataGridView

        Controls.Add(dgvStudents)
    End Sub
End Class

As a normal Windows control, when creating it, make sure you specify some of the regular characteristics such as the location, the size, the anchoring, the docking, etc. Here is an example

Public Class Exercise
    Private dgvStudents As DataGridView

    Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
        Text = "Students Records"

        dgvStudents = New DataGridView
        dgvStudents.Location = new Point(12, 12)
        Controls.Add(dgvStudents)
    End Sub
End Class

This would produce:

Data Grid View

The Columns of a Data Grid View

 

Introduction

As its name suggests, a data grid view is presented as a grid, which appears like a spreadsheet made of columns. The columns organize a data grid view in categories of information. To hold the columns of a data grid view, the DataGridView class is equipped with a property named Columns. The DataGridView.Columns property is of type DataGridViewColumnCollection defined as follows:

<ListBindableAttribute(False)> 
Public Class DataGridViewColumnCollection 
	Inherits BaseCollection 
	Implements IList, ICollection, IEnumerable

As you can see, this class implements the IList, the ICollection, and the IEnumerable interfaces. This means that you can use the DataGridViewColumnCollection class to programmatically create and manage the columns of a data grid view.

Creating a Column

One of the first actions you should perform on a data grid view consists of creating one or more columns. If you are visually creating a data grid view, on the form, click the data grid view control. In the Properties window, click Columns and click its ellipsis button. As an alternative, on the form, click the data grid view and click the button on its top right section:

Data Grid View

Then click the Edit Columns button. In both cases, the Edit Columns dialog box would come up:

Edit Columns

To create a column, click the Add button. If you had clicked the button on the top-right section of the data grid view, you can click the Add Column button. In both cases, the Add Column dialog box would come up:

Add Column

The column of a data grid view is an object of type DataGridViewColumn. Therefore, to programmatically create a column, you can declare a variable of type DataGridViewColumn. and initialize it with its default constructor. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    Dim colFirstName As DataGridViewColumn = New DataGridViewColumn

    Controls.Add(dgvStudents)
End Sub

After a new column has been added, the data grid view fires a ColumnAdded event, which is handled by the DataGridViewColumnEventArgs class.

Deleting a Column

If you do not want a certain column in your data grid view, you can remove it. If you are visually working on the data grid view, open the Edit Columns dialog box. To delete a column, click it in the Selected Columns list and click the Remove button.

To assist you with programmatically deleting a column, the DataGridViewColumnCollection class is equipped with a method named Remove and that is overloaded with two versions. To delete a column based on its name, you can use the following syntax:

Public Overridable Sub Remove(columnName As String)

To delete a column using its reference, the DataGridViewColumnCollection class provides the following version:

Public Overridable Sub Remove ( 
	dataGridViewColumn As DataGridViewColumn)

When a column has been deleted, the data grid view fires a ColumnRemoved event. This event is handled by the DataGridViewColumnEventArgs class.

The Cell Template of a Column

In our introduction, we stated that the cells under a column could be made of text boxes, combo boxes, buttons, pictures, or linked labels. When creating a column, you must specify the type of control that the cells of a column would be made of. If you are visually creating a column, in the Add Column combo box, after specifying the name, click the arrow of the Type combo box and select. To change the type of a column, open the Edit Columns dialog box and click the column in the Selected Columns list. In the Properties section, click the arrow of the ColumnType field and select the desired one:

Column Type

The data grid view considers the column type as a cell template. To support cell templates, the .NET Framework provides the DataGridViewCell class. Except for the check box, you can use the DataGridViewCell class to specify the type of cells a column should display. To do this, declare a variable of type DataGridViewCell and use the new operator to initialize it with one of the following classes:

  • DataGridViewTextBoxCell: Used to display text boxes. Here is an example:
    Dim celFullName As DataGridViewCell = new DataGridViewTextBoxCell
  • DataGridViewComboBoxCell: Used to display combo boxes. Here is an example:
    Dim celGender As DataGridViewCell = new DataGridViewComboBoxCell
  • DataGridViewButtonCell: Used to display buttons. Here is an example:
    Dim celShowResume As DataGridViewCell = new DataGridViewButtonCell
  • DataGridViewImageCell: Used to display pictures. Here is an example:
    Dim celShowPicture  As DataGridViewCell = new DataGridViewImageCell
  • DataGridViewLinkCell: Used to display linked labels. Here is an example:
    Dim celEmailAddress As DataGridViewCell = new DataGridViewLinkCell

After declaring and initializing the variable, you can assign it to the CellTemplate property of the column. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                          ByVal e As System.EventArgs) 
                          Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    Dim colFullName As DataGridViewColumn = New DataGridViewColumn
    Dim celFullName As DataGridViewCell = New DataGridViewTextBoxCell
    colFullName.CellTemplate = celFullName

    Controls.Add(dgvStudents)
End Sub

Once the new column has been built, to make it possible to actually add it to the data grid, the DataGridViewColumnCollection class is equipped with a method named Add that comes in two versions. One of its flavors uses the following syntax:

Public Overridable Function Add ( 
	dataGridViewColumn As DataGridViewColumn 
) As Integer

This version takes a DataGridViewColumn object as argument. If it succeeds in adding the new column, the method returns its index. Here are examples of calling this method:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    Dim colFullName As DataGridViewColumn = New DataGridViewColumn
    Dim celFullName As DataGridViewCell = New DataGridViewTextBoxCell
    colFullName.CellTemplate = celFullName
    dgvStudents.Columns.Add(colFullName)

    Dim colGender As DataGridViewColumn = New DataGridViewColumn
    Dim celGender As DataGridViewCell = New DataGridViewComboBoxCell
    colGender.CellTemplate = celGender
    dgvStudents.Columns.Add(colGender)

    Dim colShowResume As DataGridViewColumn = New DataGridViewColumn
    Dim celShowResume As DataGridViewCell = New DataGridViewButtonCell
    colShowResume.CellTemplate = celShowResume
    dgvStudents.Columns.Add(colShowResume)

    Dim colShowPicture As DataGridViewColumn = New DataGridViewColumn
    Dim celShowPicture As DataGridViewCell = New DataGridViewImageCell
    colShowPicture.CellTemplate = celShowPicture
    dgvStudents.Columns.Add(colShowPicture)

    Dim colEmailAddress As DataGridViewColumn = New DataGridViewColumn
    Dim celEmailAddress As DataGridViewCell = New DataGridViewLinkCell
    colEmailAddress.CellTemplate = celEmailAddress
    dgvStudents.Columns.Add(colEmailAddress)

    Controls.Add(dgvStudents)
End Sub

This would produce:

Data Grid View

As an alternative to specifying the types of cells of a column, the .NET Framework provides a class for each type of column:

  • DataGridViewTextBoxColumn: This is used to let the cells display as text boxes
  • DataGridViewComboBoxColumn: This is used to let the cells display as combo boxes
  • DataGridViewCheckBoxColumn: This is used to let the cells display as check boxes
  • DataGridViewButtonColumn: This is used to let the cells display as buttons
  • DataGridViewImageColumn: This is used to let the cells display as pictures
  • DataGridViewLinkColumn: This is used to let the cells display as linked labels

Each one of these classes inherits from the DataGridViewColumn. This means they share many characteristics they get from their common parent.

To specify the types of cells of a column, declare a variable using one of these classes and initialize it using its default constructor, then pass it to the Add() method of the Columns property of the data grid view. Here are examples:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    Dim colFullName As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn
    dgvStudents.Columns.Add(colFullName)

    Dim colGender As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn
    dgvStudents.Columns.Add(colGender)

    Dim colShowResume As DataGridViewCheckBoxColumn = 
		New DataGridViewCheckBoxColumn
    dgvStudents.Columns.Add(colShowResume)

    Dim colShowPicture As DataGridViewButtonColumn = New DataGridViewButtonColumn
    dgvStudents.Columns.Add(colShowPicture)

    Dim colEmailAddress As DataGridViewLinkColumn = New DataGridViewLinkColumn
    dgvStudents.Columns.Add(colEmailAddress)

    Dim colPicture As DataGridViewImageColumn = New DataGridViewImageColumn
    dgvStudents.Columns.Add(colPicture)

    Controls.Add(dgvStudents)
End Sub

This would produce:

Data Grid View

If you create the column to show combo boxes, to create the values of the combo box, the DataGridViewComboBoxColumn class is equipped with a property named Items. This property is of type ObjectCollection and is created inside the DataGridViewComboBoxCell class. Here is an example of calling the Add() method of this class:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    Dim colFirstName As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn
    dgvStudents.Columns.Add(colFirstName)

    Dim colLastName As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn
    dgvStudents.Columns.Add(colLastName)

    Dim colGender As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn

    colGender.Items.Add("Male")
    colGender.Items.Add("Female")
    colGender.Items.Add("Unknown")

    Controls.Add(dgvStudents)
End Sub

The Name of a Column

Because a column is an object in its own right, it has a name (an object name). If you visually create a column, a default name would be given to it in the Name text box of the Add Column dialog. You can accept that name or change it. After creating a column, to change its name, open the Edit Columns dialog box and click the column in the Selected Columns list. In the Properties section, click the (Name) field and change its value.

To programmatically specify the name of a column, you have various options. If you use the DataGridViewColumn class to create a column, it is equipped with a property named Name. Therefore, to specify the name of the column, assign a string to that property. The name of a column can be anything. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
        dgvStudents = New DataGridView
        dgvStudents.Location = New Point(10, 10)
        dgvStudents.Size = New Size(250, 100)

        Dim colFullName As DataGridViewColumn = New DataGridViewColumn
        colFullName.Name = "2 Four 1 @ U$"
        Dim celFullName As DataGridViewCell = New DataGridViewTextBoxCell
        colFullName.CellTemplate = celFullName
        dgvStudents.Columns.Add(colFullName)

        Controls.Add(dgvStudents)
End Sub

To make it simple and practical, we will use C# rules to name our columns.

If you use one of the DataGridViewControlColumn classes, we saw that they derive from the DataGridViewColumn class. Therefore, after instantiating a column using one of those classes, to specify its name, assign a string to its Name property.

The Caption of a Column

When a data grid view displays its columns, the user should be able to identify each. To make it possible, each column should display a string in the column header, the top box of a column. That string is called the caption (or text, or header text) of the column.

If you are visually creating a column, a default caption is given in the Header Text text box. You can accept that string or change it. After creating a column, to change its caption, open the Edit Columns dialog box and click the column in the Selected Columns list. In the Properties section, click the HeaderText field and change its value.

To programmatically specify or change the caption of a column, you have various options. If you specify the name of a column, the compiler would apply it as the caption of the column. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
        dgvStudents = New DataGridView
        dgvStudents.Location = New Point(10, 10)
        dgvStudents.Size = New Size(250, 100)

        Dim colFullName As DataGridViewColumn = New DataGridViewColumn
        colFullName.Name = "FullName"
        Dim celFullName As DataGridViewCell = New DataGridViewTextBoxCell
        colFullName.CellTemplate = celFullName
        dgvStudents.Columns.Add(colFullName)

        Controls.Add(dgvStudents)
End Sub

This would produce:

The name of a column is used as its caption

Otherwise, to support the caption of a column, the DataGridViewColumn class is equipped with a property named HeaderText. Therefore, to specify the caption of a column, assign a string to this property. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    Dim colFullName As DataGridViewColumn = New DataGridViewColumn
    colFullName.Name = "FullName"
    colFullName.HeaderText = "Full Name"

    Dim celFullName As DataGridViewCell = New DataGridViewTextBoxCell
    colFullName.CellTemplate = celFullName
    dgvStudents.Columns.Add(colFullName)

    Controls.Add(dgvStudents)
End Sub

This would produce:

The caption of a column

In the same way, if you use one of the DataGridViewControlColumn classes to create a column, you can assign a string to its HeaderText property to specify its caption.

So far, to programmatically create a column, we were using either the DataGridViewColumn or one of its derived DataGridViewControlColumn classes. After creating the column, we were calling a version of the DataGridViewColumnCollection.Add() method to add the new column. To make it a little simpler to create a column, the DataGridViewColumnCollection class is equipped with a second version of the Add() method. Its syntax is:

Public Overridable Function Add ( 
	columnName As String, 
	headerText As String 
) As Integer

This version allows you to create a column by specifying its object name and its caption. Here are examples:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
        dgvStudents = New DataGridView
        dgvStudents.Location = New Point(10, 10)
        dgvStudents.Size = New Size(250, 100)

        dgvStudents.Columns.Add("FirsName", "First Name")
        dgvStudents.Columns.Add("LasName", "Last Name")
        dgvStudents.Columns.Add("Gender", "Gender")

        Controls.Add(dgvStudents)
End Sub

This would produce:

Name and Caption

As you can see, the default type of a column created using the DataGridViewColumnCollection.Add(Name, Caption) method is a text box. If you want a different type of column, you should use one of the techniques we saw earlier to create the column.

The Width of a Column

The width of a column is the distance from its left to its right borders. When you create a column (whether visually or programmatically), it receives a default width. For you to visually change the width of a column, in the Edit Columns dialog box, click the column in the Selected Columns list box. Then, in the Properties section, click the Width field and change its value.

To assist you with programmatically specifying the width of a column, the DataGridViewColumn class is equipped with an integral property named Width. Therefore, to specify or change the width of a column, assign an integer to this property.

By default, when a data grid view displays its columns, the user is able to resize any of them. To do this, the user can position the mouse on the separating line of two columns, click, and drag left or right. If you want, you can allow this or prevent the user from resizing a column. This characteristic is controlled by the Resizable Boolean property of the DataGridColumn class. The default value of the DataGridColumn.Resizable property is True, which indicates that the user can resize it. To prevent this change, you can set this property to False:

Resizable

Of course, you can also control this characteristic by assigning a True or False value to the property.

There are various ways the user can resize a column. The user can position the mouse on the right border of a column header, click and hold down the mouse, then drag left or right. The user can also double-click the right border of a column. However the user does this, when the width of a column has been changed, the data grid view fires a ColumnWidthChanged event. This event is handled by the DataGridViewColumnEventArgs class. If the user double-clicks the right border of a column, the control fires a ColumnDividerDoubleClick event. This event is handled by the DataGridViewColumnDividerDoubleClickEventArgs class.

Referring to a Column

In some operations, you will need to indicate the column you want to access. If you are working visually, open the Edit Columns dialog box and click the column in the Selected Columns list.

To programmatically refer to a column, you have various options. The DataGridViewColumnCollection class is equipped with an indexed property (named Item) that allows you to refer to a column either by its index or by its object name. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    dgvStudents.Columns.Add("FirsName", "First Name")
    dgvStudents.Columns.Add("LasName", "Last Name")
    dgvStudents.Columns.Add("Gender", "Gender")

    MsgBox(dgvStudents.Columns(1).HeaderText)

    Controls.Add(dgvStudents)
End Sub

The Records of a Data Grid View

 

Introduction to Rows

After creating a data grid view and its columns, you can start populating it with values. When the data grid view comes up, the user can click a cell. When the user clicks a cell, that cell becomes highlighted, indicating that it has received focus. Here is an example:

When the user clicks a cell, that cell becomes highlighted, indicating that it has received focus

When a cell receives focus, the data grid view fires a CellEnter Event. This event is handled by the DataGridViewCellEventArgs class. This class is equipped with two properties named ColumnIndex and RowIndex. The ColumnIndex property indicates the index of the column that was clicked. The RowIndex property indicates the index of the column that was clicked.

After clicking a cell, the user can start typing if the cell is text-based. If the cell already contained a value, the user can click it first to give it focus and then edit its content. When the user starts editing the value of a cell, the data grid view fires a CellBeginEdit event, which is handled by the DataGridViewCellCancelEventArgs class. As its name suggests, the primary characteristic of this class is that it allows you to accept or reject what the user is doing. After the user has edited the value of  a cell, the data grid view fires a CellEndEdit event. This event is handled by the DataGridViewCellEventArgs class. When this ends, the cell should have a new value. Here is an example:

A New Value For A Cell

If the cell is not text-based, the user can select the check box or use the content, based on its type. Either way, when the value of a cell has changed, the data grid view fires a CellValueChanged event, which is handled by the DataGridViewCellEventArgs class, which allows you to identify the cell whose value was changed.

After specifying the value of a cell or taking the necessary action, the user can move to another cell. When a cell loses focus, the data grid view fires a CellLeave event. This event is handled by the DataGridViewCellEventArgs class, which allows you to find out what cell just lost focus.

The user can perform these operations for each cell under the columns. The row of cells at the same level under the columns is called a record. Here is an example of a record with the values Joyce, Simms, and Female:

 A Record

Each row starts with a gray box on the left side. When the user clicks a cell of a particular row, the data grid view fires a RowEnter event that indicates that the row has just received focus. Then, the gray box of that record becomes equipped with a pen icon. The RowEnter event is handled by the DataGridViewCellEventArgs class. If the user clicks a cell of another row, such as a cell above it, under it, or a column header, the data grid view fires a RowLeave event, which indicates that the previous row lost focus. The RowLeave event also is handled by the DataGridViewCellEventArgs class.

A record that has been added already displays an empty gray box. The next empty record has a gray box with a *. The line between two rows is called a row divider.

The Rows of a Data Grid View

To support the records of a data grid view, the DataGridView class is equipped with a property named Rows, which is a collection. The DataGridView.Rows property is an object of type DataGridViewRowCollection:

<ListBindableAttribute(False)> 
Public Class DataGridViewRowCollection 
	Implements IList, ICollection, IEnumerable

As you can see, this class implements the IList, the ICollection, and the IEnumerable interfaces. Since a data grid view can have many records, the records are stored in a zero-based indexed collection. The first record has an index of 0. The second has an index of 1, and so on. To support this, the DataGridViewRowCollection class is equipped with an indexed property (named Item) that is overloaded with two versions. Therefore, to refer to a record, apply the () operator to the DataGridView.Rows property. An example would be:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
        dgvStudents = New DataGridView
        dgvStudents.Location = New Point(10, 10)
        dgvStudents.Size = New Size(250, 100)

        dgvStudents.Columns.Add("FirsName", "First Name")
        dgvStudents.Columns.Add("LasName", "Last Name")
        dgvStudents.Columns.Add("Gender", "Gender")

        Controls.Add(dgvStudents)

        dgvStudents.Rows(0) . . .
End Sub

In the same way, if a data grid view contains many records, you can refer to any, based on its index. The index refers to the gray box on the left of the record. Each member of the DataGridViewRowCollection collection is an object of type DataGridViewRow. This allows you to get a reference to a row and do what is needed.

There are various things the user can do with a row header. For example, the user can click a row header. A row header that has been clicked becomes equipped with a right-pointing arrow and its cells become selected:

A column header that has been clicked becomes equipped with a right-pointing arrow its cells become selected

When the user clicks a row header, the data grid view fires a RowHeaderMouseClick event. This event is handled by the DataGridViewCellMouseEventArgs class. This class is equipped with two properties named ColumnIndex and RowIndex. The ColumnIndex property indicates the index of the column that was clicked. The RowIndex property indicates the index of the column that was clicked.

The user can also double-click a row header and you can take action if necessary. When the user double-clicks a row header, the data grid view fires a RowHeaderMouseDoubleClick event. This event is handled by the DataGridViewCellMouseEventArgs class.

The Height of a Row

When a new record is created, its row receives a default height, which is the distance from its top to its bottom borders. The user can accept or change the height of a row. To do this, the user can click and drag the bottom border of a row header. If the values in a row are too tall for a height, the bottom parts of those values may not appear. In other cases, the height of a row might be too high for the values of a row. To let the data grid view adjust the height of a row to be just as necessary, the user can double-click the bottom border of the row.

If the user double-click the bottom border of a row, the data grid view fires a RowDividerDoubleClick event. This event is handled by the DataGridViewRowDividerDoubleClickEventArgs class. The DataGridViewRowDividerDoubleClickEventArgs class is equipped with one property named RowIndex, which holds the index of the row whose bottom border was double-clicked.

The Cells of a Data Grid View

 

Introduction

A data grid view is meant to display values and these values are stored in cells. Under each column header is a box called a cell. To add a value to a data grid view, you (actually the user) click one of those cells. When a cell has been clicked, the data grid view fires a CellClick event. This event is handled by the DataGridViewCellEventArgs class. The user can also double-click a cell. In this case, the data grid view fires a CellDoubleClick event. This event is handled by the DataGridViewCellEventArgs class.

If the user clicks the content (it could be its value) of a cell, the data grid view fires a CellContentClick event. This event is handled by the DataGridViewCellEventArgs class.

After clicking a cell, the user can start typing the desired value. The user can also double-click the content of a cell. In this case, the data grid view fires a CellContentDoubleClick event. This event is handled by the DataGridViewCellEventArgs class.

The Cells of a Row

As stated already, either you or the user can create values for cells. The user can add one value at a time. You too can either create each value or add them in a group. The user must identify a cell, click it and then start typing. You too, at any time, should know what cell is receiving, or needs, attention. To assist you with identifying a cell, the DataGridViewRow class is equipped with a property named Cells. This property itself is a collection created from a class named DataGridViewCellCollection:

<ListBindableAttribute(False)> 
Public Class DataGridViewCellCollection 
	Inherits BaseCollection 
	Implements IList, ICollection, IEnumerable

This is a typical collection class that implements the IList, the ICollection, and the IEnumerable interfaces. This class allows you to refer to a record, which is primarily a collection of cells that share the same row. To support this idea of a range of cells, the DataGridViewCellCollection class is equipped with an indexed property (named Item) that is overloaded with two versions. One of the versions allows you to refer to a cell, based on the index of its column. The most left cell of a row has an index of 0. The second from left has an index of 1, and so on. 

To identify a cell in a record, you use the concept of a cell being the intersection of a row and a column. Therefore, you can use the DataGridView.Rows() indexed property to specify the record. Then access the DataGridViewRow.Cells() indexed property to specify the column under which the cell exists. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    dgvStudents.Columns.Add("FirsName", "First Name")
    dgvStudents.Columns.Add("LasName", "Last Name")
    dgvStudents.Columns.Add("Gender", "Gender")

    Controls.Add(dgvStudents)

    ' First Record
    dgvStudents.Rows(0) . . .
    ' Second Record
    dgvStudents.Rows(1) . . .
    ' Intersection of: First Record - First Column
    dgvStudents.Rows(0).Cells(0) . . .
    ' Intersection of: First Record - Second Column
    dgvStudents.Rows(0).Cells(1) . . .
    ' Intersection of: Second Record - First Column
    dgvStudents.Rows(1).Cells(0) . . .
    ' Intersection of: Second Record - Second Column
    dgvStudents.Rows(1).Cells(1) . . .
End Sub

Using the index of a column supposes that you know the exact sequence of columns. As an alternative, you can be more precise by using the object name of a column. To support this, the DataGridViewRow.Cells() indexed property has another version that takes a string as argument. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(250, 100)

    dgvStudents.Columns.Add("FirsName", "First Name")
    dgvStudents.Columns.Add("LasName", "Last Name")
    dgvStudents.Columns.Add("Gender", "Gender")

    Controls.Add(dgvStudents)

    dgvStudents.Rows(0).Cells(0)
    dgvStudents.Rows(0).Cells(1)

    dgvStudents.Rows(0).Cells("Gender") . . .
End Sub

Once you have identified a cell, you can then do in it what you want. 

The Value of a Cell

Probably the most important aspect of a cell is its content. The default content of a cell is its text. This is typical of a text-based cell. We have already seen how to identify a cell. To identify its value, the DataGridViewCell class is equipped with a property named Value. Therefore, to add a value to a cell, assign the desired string to its Value property. Here are examples:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(350, 100)

    dgvStudents.Columns.Add("FirsName", "First Name")
    dgvStudents.Columns.Add("LasName", "Last Name")
    dgvStudents.Columns.Add("Gender", "Gender")

    Controls.Add(dgvStudents)

    dgvStudents.Rows(0).Cells(0).Value = "Joyce"
    dgvStudents.Rows(0).Cells(1).Value = "Simms"
    dgvStudents.Rows(0).Cells("Gender").Value = "Female"
End Sub

This would produce:

 A Record

If a cell is a check box, to specify its value, assign True or False to its Value property. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
        dgvStudents = New DataGridView
        dgvStudents.Location = New Point(10, 10)
        dgvStudents.Size = New Size(320, 80)

    Dim colFirstName As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn
    colFirstName.Name = "FirstName"
    colFirstName.HeaderText = "First Name"
    dgvStudents.Columns.Add(colFirstName)

    Dim colLastName As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn
    colLastName.Name = "LastName"
    colLastName.HeaderText = "Last Name"
    dgvStudents.Columns.Add(colLastName)

    Dim colFullTime As DataGridViewCheckBoxColumn = New DataGridViewCheckBoxColumn
        colFullTime.Name = "FullTime"
        colFullTime.HeaderText = "Full Time?"
        colFullTime.Width = 70
        dgvStudents.Columns.Add(colFullTime)

        Controls.Add(dgvStudents)

        dgvStudents.Rows(0).Cells(0).Value = "Ernestine"
        dgvStudents.Rows(0).Cells(1).Value = "Cavier"
        dgvStudents.Rows(0).Cells(2).Value = True
End Sub

This would produce:

Check Box

If the column is a combo box, you can assign a string to its Value property. The value should be one of the items in the combo box.

If the column is configured for web links, you can assign a string to its Value property. You should make sure the string is either a valid URL or an email address. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
        dgvStudents = New DataGridView
        dgvStudents.Location = New Point(10, 10)
        dgvStudents.Size = New Size(540, 80)

    Dim colFirstName As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn
        colFirstName.Name = "FirstName"
        colFirstName.HeaderText = "First Name"
        dgvStudents.Columns.Add(colFirstName)

    Dim colLastName As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn
        colLastName.Name = "LastName"
        colLastName.HeaderText = "Last Name"
        dgvStudents.Columns.Add(colLastName)

    Dim colGender As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn
        colGender.Name = "Gender"
        colGender.Items.Add("Male")
        colGender.Items.Add("Female")
        colGender.Items.Add("Unknown")
        dgvStudents.Columns.Add(colGender)

    Dim colFullTime As DataGridViewCheckBoxColumn = New DataGridViewCheckBoxColumn
        colFullTime.Name = "FullTime"
        colFullTime.HeaderText = "Full Time?"
        colFullTime.Width = 70
        dgvStudents.Columns.Add(colFullTime)

        Dim colEmailAddress As DataGridViewLinkColumn = New DataGridViewLinkColumn
        colEmailAddress.HeaderText = "Email Address"
        colEmailAddress.Width = 120
        dgvStudents.Columns.Add(colEmailAddress)

        Controls.Add(dgvStudents)

        dgvStudents.Rows(0).Cells(0).Value = "Ernestine"
        dgvStudents.Rows(0).Cells(1).Value = "Cavier"
        dgvStudents.Rows(0).Cells(2).Value = "Female"
        dgvStudents.Rows(0).Cells(3).Value = True
        dgvStudents.Rows(0).Cells(4).Value = "caviere@emailfrance.fr"
End Sub

This would produce:

Column Link

Creating a Record

We mentioned that, when a user adds a new value into a cell, a new empty record is created under that row. Also, by default, after you have just created the columns of a data grid view, the studio adds an empty record to it. If you work programmatically, you do not get the same feature, or only one default empty record is given to you. Therefore, before creating one or more values for a record, you must make sure there is an empty record ready to receive your values. This means that you must first create a (an empty) record. You have various options.

To assist you with creating new records, the DataGridViewRowCollection class is equipped with a method named Add and that is overloaded with 4 versions. One of the versions uses the following syntax:

Public Overridable Function Add As Integer

This version of the DataGridViewRowCollection.Add() method allows you to create one empty record. Here is an example of calling it:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = new DataGridView
    dgvStudents.Location = new Point(10, 10)
    dgvStudents.Size = new Size(350, 100)

    dgvStudents.Columns.Add("FirstName", "First Name")
    dgvStudents.Columns.Add("LastName", "Last Name")
    dgvStudents.Columns.Add("Gender", "Gender")

    Controls.Add(dgvStudents)

    dgvStudents.Rows.Add()
End Sub

You may want to create many records before adding values to them. To support this, the DataGridViewRowCollection class provides another version of the Add() method. Its syntax is:

Public Overridable Function Add(count As Integer) As Integer

When calling this method, pass the desired number of records as argument. Once you have created the records, you can then add the desired values. Here is an example of calling Add():

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(350, 200)

    dgvStudents.Columns.Add("FirstName", "First Name")
    dgvStudents.Columns.Add("LastName", "Last Name")
    dgvStudents.Columns.Add("Gender", "Gender")

    Controls.Add(dgvStudents)

    dgvStudents.Rows.Add(4)

    dgvStudents.Rows(0).Cells(0).Value = "Joyce"
    dgvStudents.Rows(0).Cells(1).Value = "Simms"
    dgvStudents.Rows(0).Cells("Gender").Value = "Female"

    dgvStudents.Rows(1).Cells("FirstName").Value = "Peter"
    dgvStudents.Rows(1).Cells(1).Value = "Mukoko"
    dgvStudents.Rows(1).Cells(2).Value = "Male"
End Sub

Instead of adding the values of cells one at a time, you can store them in an array, then add the whole when it is ready. To support this, the DataGridViewRowCollection class is equipped with the following version of the Add() method:

Public Overridable Function Add(values As Object()) As Integer

 This version expects an array of objects as arguments. Here is an example:

Private Sub ExerciseLoad(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles MyBase.Load
    dgvStudents = New DataGridView
    dgvStudents.Location = New Point(10, 10)
    dgvStudents.Size = New Size(350, 200)

    dgvStudents.Columns.Add("FirstName", "First Name")
    dgvStudents.Columns.Add("LastName", "Last Name")
    dgvStudents.Columns.Add("Gender", "Gender")

    Controls.Add(dgvStudents)

    Dim AHRecord() As String = {"Adrian", "Hewitt", "Male"}
    dgvStudents.Rows.Add(AHRecord)
End Sub

 

 

Home Copyright © 2008-2016, FunctionX, Inc.