Delphi32.com - Home!
| Home/News | Downloads | Forums | D32 Magazine | Resources | Info and Facts |  
 
 Copying Selected Rows in a String Grid to the Clipboard


One of the most essential features that is lacking from the TStringGrid component (in all version of Delphi) is the ability to copy and paste information to other applications. However, this can be easily implemented through the code segment shown below.

In this code segment, the OnKeyDown event handler is used for the TStringGrid component to capture the keyboard sequence Control-C (or Control-c). The information from any of the cells that are selected (even if multiple cells are selected) is then copied to the clipboard in a tab-delimited format (which works very well with spreadsheets).

procedure TForm1.StringGrid1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
   i,j,LeftCell,TopCell : Integer;
   BottomCell, RightCell : Integer;
   TextBuf : String;
   SysClip : TClipBoard;
begin
   SysClip := TClipBoard.Create;
   //trap the Control-C or Control-c keys
   if (Shift = [ssCtrl]) and ((Key = 67) or (Key = 99)) then begin
      //get the coordinates of the selected region of the grid
      LeftCell := StringGrid1.Selection.Left;
      TopCell := StringGrid1.Selection.Top;
      BottomCell := StringGrid1.Selection.Bottom;
      RightCell := StringGrid1.Selection.Right;
      //The variable TextBuf is used to hold the information that will to to the clipboard
      TextBuf := '';
      //for all of the selected cells, copy the contents to
      //TextBuf and separate lines by returns and cells by tabs
      for i := TopCell to BottomCell do begin
         for j := LeftCell to RightCell do begin
            if j = LeftCell then
               TextBuf := TextBuf + StringGrid1.Cells[j,i]
            else
               TextBuf := TextBuf + #09 + StringGrid1.Cells[j,i];
         end;
         TextBuf := TextBuf + #13#10;
      end;
      //Now move the contents of TextBuf to the windows clipboard
      SysClip.AsText := TextBuf;
      //destroy the clipboard object , this does not affect
      //the contents in the Windows clipboard
      SysClip.Destroy;
   end;
end;

Submitted by: Tom W Khoury


 
 Hits/month  2,500,000+ 
 Downloads
 (Since May 2000)
 7,393,709 
 Total Files  6,023 
 Forum msgs  7,670 
 Articles/FAQs  70+/900+ 
Kylix
Tips n Tricks
FAQs
Knowledge Base
Bug Listings
Articles
Books
Newsgroups
Links
Submissions
Testimonials
Advertising
Contact Us
About Us
Search Amazon:
Top Selling Software at Amazon

| Home/News | Downloads | Forums | Resources | Info and Facts | Testimonials |
  Site Search:
 


Comments/Problems: Webmaster@delphi32.com
Copyright © 1998-2006, Delphi32.com. All rights reserved.
Terms of Use