How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Control


The data you display in the DataGridView control will normally come from a data source of some kind, but you might want to display a column of data that does not come from the data source. This kind of column is called an unbound column. Unbound columns can take many forms. Frequently, they are used to provide access to the details of a data row.

The following code example demonstrates how to create an unbound column of Details buttons to display a child table related to a particular row in a parent table when you implement a master/detail scenario. To respond to button clicks, implement a DataGridView.CellClick event handler that displays a form containing the child table.

There is support for this task in Visual Studio. Also see How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer


private void CreateUnboundButtonColumn()
    // Initialize the button column.
    DataGridViewButtonColumn buttonColumn =
        new DataGridViewButtonColumn();
    buttonColumn.Name = "Details";
    buttonColumn.HeaderText = "Details";
    buttonColumn.Text = "View Details";

    // Use the Text property for the button text for all cells rather
    // than using each cell's value as the text for its own button.
    buttonColumn.UseColumnTextForButtonValue = true;

    // Add the button column to the control.
    dataGridView1.Columns.Insert(0, buttonColumn);

Compiling the Code

This example requires: