delphiinheritancetstringgrid

Creating a TStringGrid class in delphi where the object array associated with the cells is specified as a more specific type


In Delphi, how can I create a class derived from the TStringGrid class such that the TObject array associated with the grids cells is of a more specific type for example TColor which would be used to specify the colour of the cell?


Solution

  • TStringGrid can hold a TObject for each cell. TColor doesn't inherit from TObject so it doesn't work.

    You could cast a TColor to a TObject but this would be a bad solution prone to future issues. And this would not work for any type (Only those having at most the size of a pointer).

    The best solution is to "box" your data into a TObject and save the instance of such an object into the StringGrid.

    TMyBoxingColorObject = class
        Data : TColor;           // Or any other datatype
    end;
    

    Don't forget to create and free the object as needed!

    You can also use generics if you have a lot of different types to box.