我在最近的一个应用程序中处理此问题的方法是创建我自己的 DataGridViewColumn 和 DataGridViewCell 类,这些类继承了现有的类之一,例如 DataGridViewTextBoxColumn 和 DataGridViewTextBoxCell。
根据您想要的单元格类型,您可以使用其他类型,例如 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 更改为我想要的。