如何:将未绑定的列添加到绑定了数据的 Windows 窗体 DataGridView 控件

更新:2007 年 11 月

您在 DataGridView 控件中显示的数据通常来自某种数据源,但您可能会想要显示并非来自该数据源的一列数据。这种列称为未绑定列。未绑定列可能有多种形式。通常,它们用于提供对数据行的详细信息的访问。

下面的代码示例演示如何创建“详细信息”按钮的未绑定列,以便在实现主/详细信息方案时显示与父表中的特定行相关的子表。若要对按钮单击作出响应,请实现 DataGridView.CellClick 事件处理程序,使之显示包含子表的窗体。

Visual Studio 中对此任务提供了支持。如何:使用设计器添加和移除 Windows 窗体 DataGridView 控件中的列
如何:使用设计器添加和移除 Windows 窗体 DataGridView 控件中的列
如何:使用设计器添加和移除 Windows 窗体 DataGridView 控件中的列
如何:使用设计器添加和移除 Windows 窗体 DataGridView 控件中的列

示例

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);
}

编译代码

此示例需要:

请参见

概念

Windows 窗体 DataGridView 控件中的数据显示模式

参考

DataGridView

其他资源

在 Windows 窗体 DataGridView 控件中显示数据