方法: データバインドされた Windows フォーム DataGridView コントロールに非バインド列を追加する
DataGridView コントロールに表示するデータは、通常なんらかのデータ ソースから取得されるデータですが、データ ソース以外からのデータの列を表示する必要が生じることがあります。 この種類の列は、非バインド列と呼ばれます。 非バインド列の形式はさまざまです。 しばしば、データ行の詳細へのアクセスに使用されます。
次のコード例では、マスター/詳細シナリオを実装する場合に、 [Details] ボタンの非バインド列を作成して、親テーブルの特定の行に関連付けられた子テーブルを表示する方法を示します。 ボタンのクリックに応答するには、子テーブルを含むフォームを表示する DataGridView.CellClick イベント ハンドラーを実装します。
Visual Studio では、このタスクに対するサポートが用意されています。 「方法: デザイナーを使用して Windows フォーム DataGridView コントロールの列を追加および削除する」も参照してください。
例
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);
}
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(0, buttonColumn)
End Sub
コードのコンパイル
この例で必要な要素は次のとおりです。
dataGridView1
という名前の DataGridView コントロール。System アセンブリおよび System.Windows.Forms アセンブリへの参照。
関連項目
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET Desktop feedback