Einzelnen Beitrag anzeigen

Oniessen

Registriert seit: 17. Feb 2010
18 Beiträge
 
#10

AW: Numerische Eingabe in Stinggrid validieren

  Alt 18. Okt 2014, 08:03
Hallo zusammen!

Ich habe die Lösung noch ein wenig angepaßt, so daß jetzt auch die Eingabe von Vorzeichen bzw. DecimalSeparator bei markiertem Text funktioniert.


Erst das TStringGrid:

Delphi-Quellcode:
// Validates a Float-only input in a Cell of a TStringGrid
procedure TMyForm.MyGridKeyPress(Sender : TObject; var Key : char);
const
  KEY_NONE = #0; // empty Char/nullCharacter
  KEY_BACKSPACE = #8;
var
  CellText:Widestring;
  selStart : integer;
  cellRow, cellCol : integer;
  DecSeparator: char;
begin
   DecSeparator:= DefaultFormatSettings.DecimalSeparator; // the StandAlone Symbol "DecimalSeparator" is deprecated


  // If selection is not empty, first delete this selection, then do the rest
  if TStringCellEditor(TStringGrid(Sender).Editor).SelLength > 0 then
     TStringCellEditor(TStringGrid(Sender).Editor).SelText:= '';


  cellRow:= (sender as TStringGrid).Row;
  cellCol:= (sender as TStringGrid).Col;
  CellText:= (sender as TStringGrid).Cells[cellCol,cellRow];
  selStart:= TStringCellEditor(TStringGrid(Sender).Editor).SelStart ; // exessive Typecasting to access SelStart

  // only Keys 0-9(numeric), #8= Backspace, '-' and DecimalSeperator allowed
  if not (Key in [KEY_BACKSPACE, '0'..'9', '-', DecSeparator])
          then Key := KEY_NONE
  // '-' and DecimalSeperator are only allowed once in the String-Input
  else if ((Key = DecSeparator) or (Key = '-')) and (Pos(Key, CellText) > 0)
          then Key := KEY_NONE
  // '-' is only allowed as first Character / SelStart is the Caret(Text-Curser) Position
  else if (Key = '-') and (selStart <> 0)
          then Key := KEY_NONE
end;

und Hier das Tedit:
Delphi-Quellcode:
// Validates a Float-only input in a TEdit
procedure TMyForm.MyEditKeyPress(Sender : TObject; var Key : char);
const
  KEY_NONE = #0; // empty Char/nullCharacter
  KEY_BACKSPACE = #8;
var
  DecSeparator: Char;
begin
  DecSeparator:= DefaultFormatSettings.DecimalSeparator; // the StandAlone Symbol "DecimalSeparator" is deprecated

  // If selection is not empty, first delete this selection, then do the rest
  if (Sender as TEdit).SelLength > 0 then (Sender as TEdit).SelText:= '';
  

  // only Keys 0-9(numeric), #8= Backspace, '-' and DecimalSeperator allowed
  if not (Key in [KEY_BACKSPACE, '0'..'9', '-', DecSeparator])
          then Key := KEY_NONE
  // '-' and DecimalSeperator are only allowed once in the String-Input
  else if ((Key = DecSeparator) or (Key = '-')) and (Pos(Key, (Sender as TEdit).Text) > 0)
          then Key := KEY_NONE
  // '-' is only allowed as first Character / SelStart is the Caret(Text-Curser) Position
  else if (Key = '-') and ((Sender as TEdit).SelStart <> 0)
          then Key := KEY_NONE
end;
Gruß, Oliver

Geändert von Oniessen (18. Okt 2014 um 08:06 Uhr)
  Mit Zitat antworten Zitat