Writing data in Delphi TDrawGrid

Question

I am new user of Delphi and now want to write some data into the DrawGrid. How can i do that?


Related Articles and Replies

Re: webmaster Guido :

You only use a TDrawGrid to display information in a tabular form, if the information can not be displayed as textual data (such as images or a combination of images and text). With a TDrawGrid, your code has to draw everything on the grid's "Canvas", its drawing surface.

A TDrawGrid doesn't have a property "Cells", like its brother TStringGrid. Your code has to calculate where to display the data and next it must draw a representation of the data on the "Canvas" of the grid. For pure text, this can be done with TextOut. The simplest example would be:

DrawGrid1.Canvas.TextOut(X, Y, 'ABC');

This will display the string 'ABC' in the font of the TDrawGrid, starting from the point with coordinates X and Y (horizontal and vertical position in pixels, relative to the left and the top of the grid). In most cases, you draw in the grid's OnDrawCell event; you receive a "rectangle" from Delphi, in which you can draw your data. An example:

procedure TForm1.DrawGrid1DrawCell(Sender: TObject; ACol,
  ARow: Integer; Rect: TRect; State: TGridDrawState);
var
  Sx, Sy: string;
begin
  Sx := IntToStr(ARow);
  Sy := IntToStr(ACol);
  with DrawGrid1 do begin
    Canvas.FillRect(Rect);
    Canvas.TextOut(Rect.Left + 2, Rect.Top + 2,
      'Row ' + Sx + ', Column ' + Sy);
    if gdFocused in State then
      Canvas.DrawFocusRect(Rect);
  end;
end;

For drawing images in a TDrawGrid, it's a bit more complicated, but I'm not going to write an entire tutorial here ;-)

If you only want to display *textual* data (of the type "string"), or if you can convert the data to a string (using IntToStr for integers, and so on...), it's a lot easier if you use a TStringGrid:

procedure TForm1.Button1Click(Sender: TObject);
var
  X, Y: integer;
  Sx, Sy: string;
begin
  with StringGrid1 do
    for X := 0 to RowCount  - 1 do
      for Y := 0 to ColCount - 1 do begin
        Sx := IntToStr(X);
        Sy := IntToStr(Y);
        Cells[Y, X] := 'Row ' + Sx + ', Column ' + Sy;
      end;
end;

With a TStringGrid, you just fill the cells and then it's done. Your code doesn't have to draw the visible cells, nor does it have to show the grid's focus rectangle, all that is done automatically.

For database tables, you use a TDBGrid.