最近のアプリケーションでこれにアプローチした方法は、DataGridViewTextBoxColumn や DataGridViewTextBoxCell などの既存のクラスの 1 つを継承して、独自の DataGridViewColumn および DataGridViewCell クラスを作成することでした。
必要なセルのタイプに応じて、Button、Checkbox、ComboBox などを使用できます。System.Windows.Forms で使用できるタイプを見てください。
セルは値をオブジェクトとして処理するため、Car クラスをセルの値に渡すことができます。
SetValue と GetValue をオーバーライドすると、値を処理するために必要なロジックを追加できます。
例えば:
public class CarCell : System.Windows.Forms.DataGridViewTextBoxCell
{
protected override object GetValue(int rowIndex)
{
Car car = base.GetValue(rowIndex) as Car;
if (car != null)
{
return car.Maker.Name;
}
else
{
return "";
}
}
}
列クラスで行う必要がある主なことは、CellTemplate をカスタム セル クラスに設定することです。
public class CarColumn : System.Windows.Forms.DataGridViewTextBoxColumn
{
public CarColumn(): base()
{
CarCell c = new CarCell();
base.CellTemplate = c;
}
}
これらのカスタム列/セルを DataGridView で使用することにより、DataGridView に多くの追加機能を追加できます。
GetFormattedValue をオーバーライドして文字列値にカスタム書式を適用することで、表示される書式を変更するためにそれらを使用しました。
また、Paint をオーバーライドして、値の条件に応じてカスタム セルの強調表示を行い、セルの Style.BackColor を値に基づいて必要なものに変更しました。