在程序设计语言中,二维数组必须先定义后使用,所谓先定义就是要确定二维数组的行数与列数及其数据类型。同样StringGrid组件在使用前也应定义其行数与列数,行数和列数分别用RowCount与ColCount属性动态确定。所以下面先介绍RowCount与ColCount属性。
(1)RowCount属性 RowCount属性用于确定StringGrid组件数据表的行数,可在程序设计时用对象监视器设定,将列数RowCount设置为20。也可在程序执行过程中用赋值语句将行数值赋于RowCount. (2)ColCount属性 ColCount属性用于确定StringGrid组件数据表的列数,可在程序设计时用对象监视器设定,将列数ColCount设置为9。也可在程序执行过程中用赋值语句将列数值赋于ColCount(3)FixedRows属性
该属性用于设置表格显示过程中固定不变的行数。如设置固定行数为1,此时用鼠标拖动表格的垂直滚动条时,第1行始终保持不变。一般第1行为标题行,标题行应始终保持可见状态。 (4)FixedCols属性 该属性用于设置表格中固定不变的列数。如设置固定列数为1,此时用鼠标拖动表格的水平滚动条时,第1列始终保持不变。 一般情况下,固定行与固定列用与表格中其他单元格不同的颜色来表示,用灰色表示,而普通单元格用白色表示。固定行与固定列的颜色可用FixedColor属性设置。 (5)FixedColor属性 FixedColor属性用于设置固定行与固定列的颜色。 (6)Cells属性 Cells属性用于表示表格中的单元格,格式如下: property Cells[Col,:Row:‘IntegeI’]:string; 其中,Col与Row分别表示单元格在表格中的列号与行号。例如: procedure TForml.:ButtonlClick(Sender:’rObject); var I,J:Integer; begin with StringGrid 1 do for I:=0 to ColCount一1 do for J:=O to RowCount—l do Cells[I,J]:=”; end; 该程序用于将stringGr。idl组件中所有单元格清空。 (7)Option属性 Option属性中有许多取逻辑值的子属性,分别用于控制表格线的显示方式,各行能否互换位置,各列能否互换位置,单元格中数据是否允许编辑等。 (8)单元格宽ColWidths,高RowHeights属性及默认单元格宽DefaultColWidth和高DefaultRowHeight,ColWidths[col] := Colwidths[Col] + 10;DefaultColWidth := 20;下面将StringGrid的使用大全贴出来,这个是转大富翁里的一个帖子:
StringGrid行列的增加和删除
typeTExCell = class(TStringGrid)publicprocedure DeleteRow(ARow: Longint);procedure DeleteColumn(ACol: Longint);procedure InsertRow(ARow: LongInt);procedure InsertColumn(ACol: LongInt);end;procedure TExCell.InsertColumn(ACol: Integer);beginColCount :=ColCount +1;MoveColumn(ColCount-1, ACol);end;procedure TExCell.InsertRow(ARow: Integer);beginRowCount :=RowCount +1;MoveRow(RowCount-1, ARow);end;procedure TExCell.DeleteColumn(ACol: Longint);beginMoveColumn(ACol, ColCount -1);ColCount := ColCount - 1;end;procedure TExCell.DeleteRow(ARow: Longint);beginMoveRow(ARow, RowCount - 1);RowCount := RowCount - 1;end;如何编写使StringGrid中的一列具有Check功能,和CheckBox效果一样
unit Unit1;
interfaceusesWindows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids;typeTForm1 = class(TForm)grid: TStringGrid;procedure FormCreate(Sender: TObject);procedure gridDrawCell(Sender: TObject; ACol, ARow: Integer;Rect: TRect; State: TGridDrawState);procedure gridClick(Sender: TObject);private{ Private declarations }public{ Public declarations }end;varForm1: TForm1;fcheck,fnocheck:tbitmap;implementation{$R *.DFM}procedure TForm1.FormCreate(Sender: TObject);vari:SmallInt;bmp:TBitmap;beginFCheck:= TBitmap.Create;FNoCheck:= TBitmap.Create;bmp:= TBitmap.create;trybmp.handle := LoadBitmap( 0, PChar(OBM_CHECKBOXES ));With FNoCheck DoBegin
width := bmp.width div 4;height := bmp.height div 3;canvas.copyrect( canvas.cliprect, bmp.canvas, canvas.cliprect );End;With FCheck Do Beginwidth := bmp.width div 4;height := bmp.height div 3;canvas.copyrect(canvas.cliprect, bmp.canvas, rect( width, 0, 2*width, height ));End;finallybmp.freeend;end;procedure TForm1.gridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);beginif not (gdFixed in State) thenwith TStringGrid(Sender).Canvas dobeginbrush.Color:=clWindow;FillRect(Rect);if Grid.Cells[ACol,ARow]='yes' thenDraw( (rect.right + rect.left - FCheck.width) div 2, (rect.bottom + rect.top - FCheck.height) div 2, FCheck )elseDraw( (rect.right + rect.left - FCheck.width) div 2, (rect.bottom + rect.top - FCheck.height) div 2, FNoCheck );end;end;procedure TForm1.gridClick(Sender: TObject);beginif grid.Cells[grid.col,grid.row]='yes' thengrid.Cells[grid.col,grid.row]:='no'elsegrid.Cells[grid.col,grid.row]:='yes';end;end.StringGrid组件Cells内容分行显示
在Tstringgrid.ondrawcell事件中:
DrawText(StringGrid1.Canvas.Handle,pchar(StringGrid1.Cells[Acol,Arow]),Length(StringGrid1.Cells[Acol,Arow]),Rect,DT_WORDBREAK or DT_LEFT);
在StringGrid怎样制作只读的列
在 OnSelectCell事件处理程序中,加入: (所有的列均设成可修改的)
if Col mod 2 = 0 thengrd.Options := grd.Options + [goEditing]elsegrd.Options := grd.Options - [goEditing];stringgrid从文本读入的问题(Save/Load a TStringGrid to/from a file?)
stringgrid从文本读入的问题(Save/Load a TStringGrid to/from a file?)
// Save a TStringGrid to a fileprocedure SaveStringGrid(StringGrid: TStringGrid; const FileName: TFileName);varf: TextFile;i, k: Integer;beginAssignFile(f, FileName);Rewrite(f);with StringGrid dobegin// Write number of Columns/RowsWriteln(f, ColCount);Writeln(f, RowCount);// loop through cellsfor i := 0 to ColCount - 1 dofor k := 0 to RowCount - 1 doWriteln(F, Cells[i, k]);end;CloseFile(F);end;// Load a TStringGrid from a fileprocedure LoadStringGrid(StringGrid: TStringGrid; const FileName: TFileName);varf: TextFile;iTmp, i, k: Integer;strTemp: String;beginAssignFile(f, FileName);Reset(f);with StringGrid dobegin// Get number of columnsReadln(f, iTmp);ColCount := iTmp;// Get number of rowsReadln(f, iTmp);RowCount := iTmp;// loop through cells & fill in valuesfor i := 0 to ColCount - 1 dofor k := 0 to RowCount - 1 dobeginReadln(f, strTemp);Cells[i, k] := strTemp;end;end;CloseFile(f);end;// Save StringGrid1 to 'c:.txt':procedure TForm1.Button1Click(Sender: TObject);beginSaveStringGrid(StringGrid1, 'c:.txt');end;// Load StringGrid1 from 'c:.txt':procedure TForm1.Button2Click(Sender: TObject);beginLoadStringGrid(StringGrid1, 'c:.txt');end;*******************************************打开一个已有的文本文件,并将内容放到stringgrid中,文本行与stringgrid行一致; 在文本中遇到空格则放入下一cells.搞定!注意,我只写了一个空格间隔的,你自己修改一下splitstring可以用多个空格分隔!procedure TForm1.Button1Click(Sender: TObject);varaa,bb:tstringlist;i:integer;beginaa:=tstringlist.Create;bb:=tstringlist.Create;aa.LoadFromFile('c:.txt');for i:=0 to aa.Count-1 dobeginbb:=SplitString(aa.Strings[i],' ');stringgrid1.Rows[i]:=bb;end;aa.Free;bb.Free;end;其中splitstring为:function SplitString(const source,ch:string):tstringlist;vartemp:string;i:integer;beginresult:=tstringlist.Create;temp:=source;i:=pos(ch,source);while i<>0 dobeginresult.Add(copy(temp,0,i-1));delete(temp,1,i);i:=pos(ch,temp);end;result.Add(temp);end;StringGrid组件Cells内容对齐在StringGrid的DrawCell事件中添加类似的代码就可以了:VARvCol, vRow : LongInt;beginvCol := ACol; vRow := ARow;WITH Sender AS TStringGrid, Canvas DOIF vCol = 2 THEN BEGIN ///对于第2列设置为右对齐SetTextAlign(Handle, TA_RIGHT);FillRect(Rect);TextRect(Rect, Rect.RIGHT-2, Rect.Top+2, Cells[vCol, vRow]);END;end;当我将StringGird的options属性中包含goRowSelect项时每当我选中StringGrid中一行, 则选中行用深蓝色显示,我想将深蓝色改为其他颜色应怎样该?
当我将StringGird的options属性中包含goRowSelect项时每当我选中StringGrid中一行, 则选中行用深蓝色显示,我想将深蓝色改为其他颜色应怎样该?
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;Rect: TRect; State: TGridDrawState);beginWith StringGrid1 dobeginIf (ARow= Krow) and not (acol = 0) thenbeginCanvas.Brush.Color :=clYellow;// ClBlue;Canvas.FillRect(Rect);Canvas.font.color:=ClBlack;Canvas.TextOut(rect.left , rect.top, cells[acol, arow]);end;end;end;procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol,ARow: Integer; var CanSelect: Boolean);beginkrow := Arow; //*kcol := Acol;end; 注意:必须把变量KROW的值初始为1或其他不为0的值,否则如果锁定第一行的话,第一行的颜色将被自设颜色取代,而锁定行不会被重画。怎么改变StringGrid控件某一列的背景和某一列的只读属性,StringGrid控件标题栏的对齐.
怎么改变StringGrid控件某一列的背景和某一列的只读属性,StringGrid控件标题栏的对齐.
请参考以下代码:在OnDrawCell事件中处理背景色。程序如下://将第二列背景变为红色。procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;Rect: TRect; State: TGridDrawState);beginif not((acol=1) and (arow>=stringgrid1.fixedrows)) then exit;with stringgrid1 dobegincanvas.Brush.color:=clRed;canvas.FillRect(Rect);canvas.TextOut(rect.left+2,rect.top+2,cells[acol,arow])end;end;//加入如下代码,那么StringGrid的第四列就只读了.其他列非只读procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);beginwith StringGrid1 do beginif ACol = 4 thenOptions := Options - [goEditing]else Options := Options + [goEditing];end;procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);vardx,dy:byte;beginif (acol = 4) and not (arow = 0) thenwith stringgrid1 dobegincanvas.Brush.color := clYellow;canvas.FillRect(Rect);canvas.font.color := clblue;dx:=2;//调整此值,控制字在网格中显示的水平位置dy:=2;//调整此值,控制字在网格中显示的垂直位置canvas.TextOut(rect.left+dx , rect.top+dy , cells[acol, arow]);end;//控制标题栏的对齐if (arow = 0) thenwith stringgrid1 dobegincanvas.Brush.color := clbtnface;canvas.FillRect(Rect);dx := 12; //调整此值,控制字在网格中显示的水平位置dy := 5; //调整此值,控制字在网格中显示的垂直位置canvas.TextOut(rect.left + dx, rect.top + dy, cells[acol, arow]);end;end;在stringGrid中使用回车键模拟TAB键切换单元格的功能实现
......
procedure TForm1.StringGrid1KeyPress(Sender: TObject; var Key: Char);labelnexttab;beginif key=#13 thenbeginkey:=#0;nexttab:if (stringgrid1.Col<stringgrid1.ColCount-1) thenbeginstringgrid1.Col:=stringgrid1.Col+1;endelsebeginif stringgrid1.Row>=stringgrid1.RowCount-1 thenstringgrid1.RowCount:=stringgrid1.rowCount+1;stringgrid1.Row:=stringgrid1.Row+1;stringgrid1.Col:=0;goto nexttab;end;end;end;.........stringgrid如何清空
with StringGrid1 do for I := 0 to ColCount - 1 do Cols[I].Clear;
选中某单元格,然后在该单元格中修改
-> 选中某单元格,然后在该单元格中修改
设置属性:StringGrid1.Options:=StringGrid1.Options+[goEditing];让记录在StringGrid中分页显示
在Uses中加入: ADOInt
//首先设定PageSize,取出PageCountprocedure TForm1.Button1Click(Sender: TObject);beginADoquery1.Recordset.PageSize :=spinedit1.Value;Edit1.Text := IntToStr(ADoquery1.Recordset.PageCount);ShowData(spinedit2.Value);end; //然后将AbsolutePage的数据乾坤大挪移到StringGrid1中 procedure TForm1.ShowData(page:integer);variRow, iCol, iCount : Integer;rs : ADOInt.Recordset;beginADoquery1.Recordset.AbsolutePage:=Page;Currpage:=page; iRow := 0;iCol := 1;stringgrid1.Cells[iCol, iRow] := 'FixedCol1';Inc(iCol);stringgrid1.Cells[iCol, iRow] := 'FixedCol2';Inc(iRow);Dec(iCol);rs := adoquery1.Recordset;for iCount := 1 to SpinEdit1.Value do beginstringgrid1.Cells[iCol, iRow] := rs.Fields.Get_Item('FieldName1').Value;Inc(iCol);stringgrid1.Cells[iCol, iRow] := rs.Fields.Get_Item('FieldName1').Value;Inc(iRow);Dec(iCol);rs.MoveNext;end;//上一页 procedure TForm1.Button2Click(Sender: TObject);beginIf (CurrPage)<>1 thenShowData(CurrPage-1);end;//下一页procedure TForm1.Button3Click(Sender: TObject);beginIf CurrPage<>ADoquery1.Recordset.PageCount thenShowData(CurrPage+1);end;打印StringGrid的程序源码
这段代码没有看懂,但是可能有的朋友需要,所以共享一下子 :)
procedure TForm1.SpeedButton11Click(Sender: TObject);VarIndex_R ,ALeft: Integer;Index : Integer;beginStringGrid_File('D:\AAA.TXT');if Not LinkTextFile thenbeginShowMessage('失败');Exit;end;//QuickRep1.DataSet := ADOTable1;Index_R := ReSize(StringGrid1.Width);ALeft := 13;Create_Title(TitleBand1,ALeft,24,HeaderControl1.Sections.Items[0].Width,20,HeaderControl1.Sections[0].Text,taLeftJustify);with Create_QRDBText(DetailBand1,ALeft,8,StringGrid1.ColWidths[0],20,StringGrid1.Font,taLeftJustify) dobeginDataSet := ADOTable1;DataField := ADOTable1.Fields[0].DisplayName;end;ALeft := ALeft + StringGrid1.ColWidths[0] * Index_R + Index_R;For Index := 1 to ADOTable1.FieldCount - 1 dobeginCreate_VLine(TitleBand1,ALeft - 13,16,1,40);Create_Title(TitleBand1,ALeft,24,HeaderControl1.Sections.Items[Index].Width,20,HeaderControl1.Sections[Index].Text,taLeftJustify);Create_VLine(DetailBand1,ALeft - 13,-1,1,31);with Create_QRDBText(DetailBand1,ALeft ,8,StringGrid1.ColWidths[Index] * Index_R,20,StringGrid1.Font,taLeftJustify) dobeginDataSet := ADOTable1;DataField := ADOTable1.Fields[Index].DisplayName;end;ALeft := ALeft + StringGrid1.ColWidths[Index] * Index_R + Index_R;end;QuickRep1.Preview;end;function TForm1.ReSize(AGridWidth: Integer): Integer;beginResult := Trunc(718 / AGridWidth);end;function TForm1.StringGrid_File(AFileName: String): Boolean;varStrValue : String;Index : Integer;ACol , ARow : Integer;AFileValue : System.TextFile;beginStrValue := '';TryAssignFile(AFileValue , AFileName);ReWrite(AFileValue);StrValue := HeaderControl1.Sections[0].Text;For Index := 1 to HeaderControl1.Sections.Count - 1 doStrValue := StrValue + ',' + HeaderControl1.Sections[Index].Text;Writeln(AFileValue,StrValue);StrValue := '';For ARow := 0 To StringGrid1.RowCount - 1 dobeginStrValue := '';StrValue := StringGrid1.Cells[0,ARow];For ACol := 1 To StringGrid1.ColCount - 1 dobeginStrValue := StrValue + ', ' + StringGrid1.Cells[ACol,ARow];end;Writeln(AFileValue,StrValue);end;FinallyCloseFile(AFileValue);end;end;function TForm1.LinkTextfile: Boolean;beginResult := False;with ADOTable1 dobegin{ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;' +'Data Source= D:\;Extended Properties=Text;' +'Persist Security Info=False';TableName := 'AAA#TXT';Open; }if Active thenResult := True;end;end;function TForm1.Create_QRDBText(Sender: TWinControl; ALeft, ATop, AWidth,AHight: Integer; AFont: TFont; AAlignMent: TAlignment): TQRDBText;varAQRDBText : TQRDBText;beginAQRDBText := TQRDBText.Create(Nil);with AQRDBText dobeginParent := Sender;Left := ALeft;Top := ATop;Width := AWidth;Height := AHight;AlignMent := AAlignMent;Font.Assign(AFont);end;Result := AQRDBText;end;function TForm1.Create_VLine(Sender: TWinControl; ALeft, ATop, AWidth,AHight: Integer): TQRShape;varAQRShapeV : TQRShape;beginAQRShapeV := TQRShape.Create(Nil);with AQRShapeV dobeginParent := Sender;Left := ALeft;Top := ATop;Width := AWidth;Height := AHight;end;Result := AQRShapeV;end;procedure TForm1.Create_Title(Sender: TWinControl; ALeft, ATop, AWidth,AHight: Integer; ACaption: String; AAlignMent: TAlignment);varAQRLabel : TQRLabel;beginAQRLabel := TQRLabel.Create(Nil);with AQRLabel dobeginParent := Sender;Left := ALeft;Top := ATop;Width := AWidth;AlignMent := AAlig如何实现在stringgrid中删除鼠标点中的那一行,下一行再顶上的效果?
procedure TForm1.Button1Click(Sender: TObject);
varSel : TGridRect;beginSel := StringGrid1.Selection;DeleteRow(Sel.Top);end;// delete rowprocedure TForm1.DeleteRow(Row: Integer);vari : integer;beginif (Row < StringGrid1.RowCount) and (Row > Stringgrid1.FixedRows-1) thenif Row < StringGrid1.RowCount - 1 thenbeginfor i := Row to StringGrid1.RowCount-1 doStringGrid1.Rows[i] := StringGrid1.Rows[i+1];StringGrid1.RowCount := StringGrid1.RowCount - 1;endelse stringGrid1.Rows[Row].Clear;end;