Home > Articles > Programming > Windows Programming

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

Custom Column Content with Unbound Columns

Now that you understand how to programmatically create columns and rows, and populate them with values, you may be wondering if you have to go to all that trouble any time you want to present content in a cell that isn’t bound to data. The good news is that there is a faster way for most scenarios where you want to present unbound data. You will need to programmatically create all the columns in the grid (although you can get the designer to write this code for you too, as shown later), but you can use events to make populating the values a little easier, especially when you mix bound data with unbound columns.

An unbound column is a column that isn’t bound to data. You add unbound columns to a grid programmatically, and you populate the column’s cells either programmatically as shown in the previous section or by using events as shown in this section. You can still add columns to the grid that are automatically bound to columns or properties in the data items of the data source. You do this by setting the DataPropertyName property on the column after it is created. Then you can add unbound columns as well. The rows of the grid will be created when you set the grid’s DataSource property to the source as in the straight data-binding case, because the grid will iterate through the rows or objects in the data collection, creating a new row for each.

There are two primary ways to populate the contents of unbound columns: handling the RowsAdded event or handling the CellFormatting event. The former is a good place to set the cell’s value to make it available for programmatic retrieval later. The latter is a good place to provide a value that will be used for display purposes only and won’t be stored as part of the data retained by the grid cells collection. The CellFormatting event can also be used to transform values as they are presented in a cell to something different than the value that is actually stored in the data that sits behind the grid.

To demonstrate this capability, let’s look at a simple example.

  1. Start a new Windows application project in Visual Studio 2005, and add a new data source to the project for the Customers table in the Northwind database (this is described in Chapter 1—here are the basic steps):
    1. Select Data > Add New Data Source.
    2. Select Database as the data source type.
    3. Select or create a connection to the Northwind database.
    4. Select the Customers table from the tree of database objects.
    5. Name the data set CustomersDataSet and finish the wizard.

      At this point you have an empty Windows Forms project with a typed data set for Customers defined.

  2. Add a DataGridView and BindingSource to the form from the Toolbox, naming them m_CustomersGrid and m_CustomersBindingSource respectively.
  3. Add the code in Listing 6.1 to the constructor for the form, following the call to InitializeComponents.

    Example 6.1. Dynamic Column Construction

    public Form1()
       // Get the data
       CustomersTableAdapter adapter = new CustomersTableAdapter();
       m_CustomersBindingSource.DataSource = adapter.GetData();
       // Set up the grid columns
       m_CustomersGrid.AutoGenerateColumns = false;
       int newColIndex = m_CustomersGrid.Columns.Add("CompanyName",
          "Company Name");
       m_CustomersGrid.Columns[newColIndex].DataPropertyName =
       newColIndex = m_CustomersGrid.Columns.Add("ContactName",
          "Contact Name");
       m_CustomersGrid.Columns[newColIndex].DataPropertyName =
       newColIndex = m_CustomersGrid.Columns.Add("Phone","Phone");
       m_CustomersGrid.Columns[newColIndex].DataPropertyName = "Phone";
       newColIndex = m_CustomersGrid.Columns.Add("Contact", "Contact");
       // Subscribe events
       m_CustomersGrid.CellFormatting += OnCellFormatting;
       m_CustomersGrid.RowsAdded += OnRowsAdded;
       // Data bind
       m_CustomersGrid.DataSource = m_CustomersBindingSource;

    This code first retrieves the Customers table data using the table adapter’s GetData method. As discussed earlier in the book, the table adapter was created along with the typed data set when you added the data source to your project. It sets the returned data table as the data source for the binding source. The AutoGenerateColumns property is set to false, since the code programmatically populates the columns collection. Then four text box columns are added to the grid using the overload of the Add method on the Columns collection, which takes a column name and the header text. The first three columns are set up for data binding to the Customers table’s CompanyName, ContactName, and Phone columns by setting the DataPropertyName property on the column after it is created. The fourth column is the unbound column and is simply created at this point through the call to the Add method. It will be populated later through events.

    Finally, the events of interest are wired up to the methods that will handle them using delegate inference. Using this new C# feature, you don’t have to explicitly create an instance of a delegate to subscribe a handler for an event. You just assign a method name that has the appropriate signature for the event’s delegate type, and the compiler will generate the delegate instance for you. In Visual Basic, you use the AddHandler operator, which has always operated similarly.

    When the data source is set on the grid and the grid is rendered, the grid iterates through the rows of the data source and adds a row to the grid for each data source row, setting the values of the bound column cells to the corresponding values in the data source. As each row is created, the RowsAdded event is fired. In addition, a series of events are fired for every cell in the row as it is created.

  4. Add the following method as the handler for the CellFormatting event:
    private void OnCellFormatting(object sender,
       DataGridViewCellFormattingEventArgs e)
        if (e.ColumnIndex == m_CustomersGrid.Columns["Contact"].Index)
           e.FormattingApplied = true;
           DataGridViewRow row = m_CustomersGrid.Rows[e.RowIndex];
           e.Value = string.Format("{0} : {1}",

    As previously mentioned, you can use the CellFormatting event if you are programmatically setting the displayed values for the cells. The event argument that is passed in to the CellFormatting event exposes a number of properties to let you know what cell is being rendered. You can use the ColumnIndex to determine which column the event is being fired for. It is checked against the index of the Contact column using a lookup in the Columns collection.

    Once it is determined that this is the column you want to supply a programmatic value for, you can obtain the actual row being populated using the RowIndex property on the event argument. In this case, the code just concatenates the ContactName and Phone from the row to form a contact information string using the String.Format method, and sets that string as the value on the Contact column.

    In other situations, you may use the CellFormatting event to do something like look up a value from another table, such as using a foreign key, and use the retrieved value as the displayed value in the unbound column. It also sets the FormattingApplied property on the event argument to true. This is very important to do; it signals the grid that this column is being dynamically updated. If you fail to do this, you will get an infinite loop if you also set the column to have its size automatically determined, as discussed in a later section.

    It should be noted that the code example for the CellFormatting event is fairly inefficient from a performance perspective. First, you wouldn’t want to look up the column’s index by name in the column collection every time. It would be more efficient to look it up once, store it in a member variable, and then use that index directly for comparison. I went with the lookup approach in this sample to keep it simple and easy to read—so you could focus on the grid details instead of a bunch of performance-oriented code. Besides, this is a somewhat contrived example anyway; it’s just meant to demonstrate how to create an unbound column.

    If you want to set the actual stored cell values of unbound columns in the grid, a better way to do this is to handle the RowsAdded event. As you might guess from the name, this event is fired as rows are added to the grid. By handling this event, you can populate the values of all the unbound cells in a row in one shot, which is slightly more efficient than having to handle the CellFormatting event for every cell. The RowsAdded event can be fired for one row at a time if you are programmatically adding rows in a loop, or it can be fired just once for a whole batch of rows being added, such as when you data bind or use the AddCopies method of the rows collection. The event argument to RowsAdded contains properties for RowIndex and RowCount; these properties let you iterate through the rows that were added to update the unbound column values in a loop. The following method shows an alternative approach for populating the grid’s Contact column from the previous example, using the RowsAdded method instead of the CellFormatting event:

    private void OnRowsAdded(object sender,
       DataGridViewRowsAddedEventArgs e)
       for (int i = 0; i < e.RowCount; i++)
          DataGridViewRow row = m_CustomersGrid.Rows[e.RowIndex + i];
          row.Cells["Contact"].Value = string.Format("{0} : {1}",

    This code obtains the current row being set in the loop by indexing into the Rows collection with the RowIndex property from the event argument and a loop index offset up to the number of rows that are affected when this event fires. It then uses the existing data in that row’s other columns to compute the contents of the current row. For a real-world application, you could obtain or compute the value of the unbound columns in the row in the loop instead.

  • + Share This
  • 🔖 Save To Your Account


comments powered by Disqus