共用方式為


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 System.Windows.Forms.DataGridView.CellClick event handler that displays a form containing the child table.

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

Example

Private Sub CreateUnboundButtonColumn()

    ' Initialize the button column.
    Dim buttonColumn As New DataGridViewButtonColumn

    With buttonColumn
        .HeaderText = "Details"
        .Name = "Details"
        .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.
        .UseColumnTextForButtonValue = True
    End With

    ' Add the button column to the control.
    dataGridView1.Columns.Insert(1, buttonColumn)

End Sub
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(1, buttonColumn);
}

Compiling the Code

This example requires:

See Also

Reference

DataGridView

Concepts

Data Display Modes in the Windows Forms DataGridView Control

Other Resources

Displaying Data in the Windows Forms DataGridView Control