How to display bitmaps in a TDBGrid (Views: 1216)
Problem/Question/Abstract: How can I add a bitmap to an individual cell in a TDBGrid and save the grid as a bitmap afterwards? Answer: Solve 1: To display a bitmap in a cell, set DefaultDrawing to False and create a DrawDataCell handler similar to the following: procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState) var Graf: TBitmap; begin if Field is TBlobField then begin Graf := TBitmap.Create; Graf.Assign(Field); DBGrid1.Canvas.StretchDraw(Rect, Graf); Graf.Free; end else begin DBGrid1.Canvas.TextOut(Rect.Left + 1, Rect.Top + 1, Field.DisplayText); end; end; Solve 2: To display the bitmap: procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var MyRect: TRect; MyImageIndex: Integer; begin DBGrid1.Canvas.FillRect(Rect); MyImageIndex := Column.Index mod 2; ImageList1.Draw(DBGrid1.Canvas, Rect.Left + 2, Rect.Top + (Rect.Bottom - Rect.Top - ImageList1.Height) div 2, MyImageIndex, Column.Grid.Enabled); MyRect := Rect; MyRect.Left := MyRect.Left + ImageList1.Width + 4; DBGrid1.DefaultDrawColumnCell(MyRect, DataCol, Column, State); end; To save the grid: procedure TForm1.Button1Click(Sender: TObject); var MyBitmap: TBitmap; begin MyBitmap := TBitmap.Create; try MyBitmap.Width := DBGrid1.ClientWidth; MyBitmap.Height := DBGrid1.ClientHeight; MyBitmap.Canvas.Brush := DBGrid1.Brush; MyBitmap.Canvas.FillRect(DBGrid1.ClientRect); MyBitmap.Canvas.Lock; try DBGrid1.PaintTo(MyBitmap.Canvas.Handle, 0, 0); Clipboard.Assign(MyBitmap); finally MyBitmap.Canvas.Unlock; end; finally MyBitmap.Free; end; end; |