2004. december 26., vasárnap

How to store a text file in a resource and display the lines in a TStringGrid at runtime


Problem/Question/Abstract:

I am trying to work out how to store approximately 1000 lines of text (3 columns, 30 chars each) inside an application. I want to read the values and then display them in a TStringGrid and do some further manipulation.

Answer:

If you want to read the data into a stringgrid a way to do that without building a class around the resource data would be this. You start by placing the data into a file and the file into a resource as detailed in Tip Number 1004. Loading this data into a TStringGrid would work like this:


procedure LoadResourceIntoGrid(grid: TStringGrid);
var
  rs: TResourceStream;
  numElements: Integer;
  datarec: TFileData;
  i: Integer;
begin
  rs := TResourceStream.Create(hInstance, 'FILEDATA', RT_RCDATA);
  try
    numElements := rs.Size div Sizeof(numElements);
    grid.Perform(WM_SETREDRAW, 0, 0);
    try
      grid.RowCount := numElements + 1; {assuming a header row}
      {following assumes grids colcount has been set correctly already}
      for i := 1 to numElements do
      begin
        rs.ReadBuffer(datarec, sizeof(datarec));
        grid.Cells[grid.FixedCols, i] := datarec.col1;
        grid.Cells[grid.FixedCols + 1, i] := datarec.col2;
        grid.Cells[grid.FixedCols + 2, i] := datarec.col3;
      end;
    finally
      grid.Perform(WM_SETREDRAW, 1, 0);
      grid.Invalidate;
    end;
  finally
    rs.free
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése