自定义数据网格视图单元格

本文关键字:视图 单元格 网格 数据网 数据 自定义 | 更新日期: 2023-09-27 18:26:55

我正在做一个项目,需要在DataGridView单元格中添加一个字段(我们称之为字段)。这样做的目的是能够在DataGriidView单元格中添加一个额外的字段,这将使项目的其余部分更加容易。

我创建了以下内容:

public class CustomGridRow:DataGridRow{}
public class CustomGridColumn:DataGridViewColumn
{
 public CustomGridColumn 
  {
   This.TemplateCell = new CustomGridTextBoxCell()
  }
}
public class CustomGridTextBoxCell: DataGridViewTextBoxCell
{
 public string field;
}

问题:如果我创建一个类(这就是我想要实现的):

 public class CustomGridCell: DataGridViewCell{}

将字段移到CustomGridCell,我希望CustomGridTextBoxCell从新的CustomGridCell继承,但它已经有一个基类DataGridViewCell,C#不允许一个类继承两个基类。

我的理解是解决方案来自Interfaces?知道怎么修吗?

自定义数据网格视图单元格

尝试

class CustomDataGridColumn : DataGridViewColumn
{
     this.CellTemplate = new CustomGridTextBoxCell();
}
class CustomGridTextBoxCell : CustomGridCell
{
}
class CustomGridCell : DataGridViewCell
{
    public string fieldA { get; set; }
    public CustomGridCell()
    {
    }
}

假设我理解你想做什么,我想你可以做一些类似的事情:

class CustomGridTextBoxCell : CustomGridCell
{
    public CustomGridTextBoxCell(string field) 
        : base(field)
    {
    }
}
abstract class CustomGridCell : DataGridViewCell
{
    private string _field;
    public CustomGridCell(string field)
    {
        this._field = field;
    }
    public string field
    {
        get { return this._field; }
    }
}

注意:我还没有测试过这个,它只是一个10岁的初学者。

更新:如果你把抽象类改成这样,那怎么办

abstract class CustomGridCell : DataGridViewCell
{
    public string field { get; set; };
    public CustomGridCell(string field)
    {
        this.field = field;
    }
}

更新

你也可以试试:

class CustomDataGridColumn : DataGridViewColumn
{
     this.CellTemplate = new CustomGridTextBoxCell();
}
class CustomGridTextBoxCell : CustomGridCell
{
}
class CustomGridCell : DataGridViewCell
{
    public string fieldA { get; set; }
    public CustomGridCell()
    {
    }
}