一个stringgrid问题,感觉有点怪(100分)

一少

Unregistered / Unconfirmed
GUEST, unregistred user!
第一行第一列stringgrid1.cells[0,0]:='2';
我想实现在第一行第二列输入"3"的时候,第一行第三列自动写出2*3的结果6。

我是这样写的,在onkeypress事件中
stringgrid1.cells[2,0]:=inttostr(strtoint(stringgrid1.cells[0,0])*strtoint(stringgrid1.cells[1,0]));
本以为没什么问题的,测试一下才发现:
当我输入3的时候,不显示结果
写入33,则显示2*3的结果6
写入333,显示2*33的结果66

看来在按键之前已经触发这个事件了 ,想来想去不知如何解决,哪位朋友帮忙看看!不甚感激!
 
试试在onchange中执行
 
stringgrid1.cells[2,0]:=inttostr(strtoint(key)*strtoint(stringgrid1.cells[1,0]));
 
找出问题了,在OnKeyUp中试试
 
我试验的代码:
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, StdCtrls;

type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure StringGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
begin
stringgrid1.cells[0,0]:='2';
end;

procedure TForm1.StringGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
try
stringgrid1.cells[2,0]:=inttostr(strtoint(stringgrid1.cells[0,0])*strtoint(stringgrid1.cells[1,0]));
except
end;
end;

end.
 
var
Form1: TForm1;
Row,Col:integer;

procedure TForm1.StringGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
with StringGrid1 do
if (row=1) and (col=2) then begin
cells[3,1]:=IntToStr(StrToInt(cells[2,1])* StrToInt(cells[1,1]));
end;
end;
procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
Row:=Arow;
Col:=ACol;
end;
 
更好一点:
procedure TForm1.StringGrid1KeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['0'..'9']) and not (Key in [#13]) and not (Key in [#8]) then
Key := Chr(0);//除了数字键,Backspace键,回车键其余键无效,
end;

procedure TForm1.StringGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
with StringGrid1 do
if (row=1) and ((col=2) or (col=1)) then
if (cells[2,1]<>'') and (cells[1,1]<>'') then
cells[3,1]:=IntToStr(StrToInt(cells[2,1])* StrToInt(cells[1,1]));
end;
 
你的问题我试过了,没事呀!
 
to 一少
》》第一行第一列stringgrid1.cells[0,0]:='2';
一般stringgrid1.cells[0,0]固定的,因此我改为stringgrid1.cells[1,1]
 
多人接受答案了。
 
顶部