Помогите с кодом в Delphi

Discussion in 'С/С++, C#, Rust, Swift, Go, Java, Perl, Ruby' started by blednii, 2 Nov 2008.

  1. blednii

    blednii Elder - Старейшина

    Joined:
    12 Jun 2007
    Messages:
    160
    Likes Received:
    23
    Reputations:
    -7
    Доброго времени суток.
    Имеется такой вот код, с ним проводятся простые мат операции, как сделать чтоб нельзя было вводить ничего кроме цифр и если поля не заполненны не выбивала стандартная ошибка.
    Сам код:

    Code:
    procedure TForm1.Button1Click(Sender: TObject);
    begin
    if (Edit1.Text='') or (Edit2.Text='') or (Edit3.Text='')or (Edit4.Text='') then
    ShowMessage('Все поля обязательны к заполнению');
    if (Edit1.Text<>'') and (Edit2.Text<>'') and (Edit3.Text<>'')and (Edit4.Text<>'') then
    Label9.Caption:='Спасибо за использование!';
    a:=StrToInt(Edit1.Text);
    b:=StrToInt(Edit2.Text);
    c:=StrToInt(Edit3.Text);
    d:=StrToInt(Edit4.Text);
    e:=1-d/100;
    f:=b/a*c*e;
    g:=b/a*c;
    Label6.Caption:=FloatToStr(f);
    Label8.Caption:=FloatToStr(g);
    
    end;
    
    Спасибо за внимание.
     
  2. cremator (c)

    cremator (c) Elder - Старейшина

    Joined:
    20 Jun 2008
    Messages:
    258
    Likes Received:
    72
    Reputations:
    0
    procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
    begin
    if not(key in ['0'..'9']) then key:=#0;
    end;
    procedure TForm1.Edit2KeyPress(Sender: TObject; var Key: Char);
    begin
    if not(key in ['0'..'9']) then key:=#0;
    end;
    procedure TForm1.Edit3KeyPress(Sender: TObject; var Key: Char);
    begin
    if not(key in ['0'..'9']) then key:=#0;
    end;
    procedure TForm1.Edit4KeyPress(Sender: TObject; var Key: Char);
    begin
    if not(key in ['0'..'9']) then key:=#0;
    end;
     
  3. begin_end

    begin_end Green member

    Joined:
    4 Jan 2007
    Messages:
    259
    Likes Received:
    596
    Reputations:
    476
    Подмена символов, не являющихся цифрами - хорошее дополнение, хотя описываемую проблему не решает. Кроме этого в приведенном коде, минимально его модифицируя, следует сделать так:
    Code:
    procedure TForm1.Button1Click(Sender: TObject);
    begin
     if (Edit1.Text<>'') and (Edit2.Text<>'') and (Edit3.Text<>'')and (Edit4.Text<>'') then
      begin
       Label9.Caption:='Спасибо за использование!';
       a:=StrToInt(Edit1.Text);
       b:=StrToInt(Edit2.Text);
       c:=StrToInt(Edit3.Text);
       d:=StrToInt(Edit4.Text);
       e:=1-d/100;
       f:=b/a*c*e;
       g:=b/a*c;
       Label6.Caption:=FloatToStr(f);
       Label8.Caption:=FloatToStr(g);
      end else ShowMessage('Все поля обязательны к заполнению');
    end;
    Ошибка "' ' is not a valid integer value" в указанном случае более не вылезет, хотя может появиться при вставке любого текста из буфера обмена в поля (м.б. еще дополнительно вводить проверку?).
     
    _________________________
    2 people like this.
  4. blednii

    blednii Elder - Старейшина

    Joined:
    12 Jun 2007
    Messages:
    160
    Likes Received:
    23
    Reputations:
    -7
    Вот это выходит


    [Error] MainFormUnit.pas(100): Declaration of 'Edit1KeyPress' differs from previous declaration
    [Error] MainFormUnit.pas(102): Undeclared identifier: 'key'
    [Error] MainFormUnit.pas(104): Declaration of 'Edit2KeyPress' differs from previous declaration
    [Error] MainFormUnit.pas(106): Undeclared identifier: 'key'
    [Error] MainFormUnit.pas(108): Declaration of 'Edit3KeyPress' differs from previous declaration
    [Error] MainFormUnit.pas(110): Undeclared identifier: 'key'
    [Error] MainFormUnit.pas(112): Declaration of 'Edit4KeyPress' differs from previous declaration
    [Error] MainFormUnit.pas(114): Undeclared identifier: 'key'
    [Fatal Error] sellercalc.dpr(11): Could not compile used unit 'MainFormUnit.pas'
     
  5. cremator (c)

    cremator (c) Elder - Старейшина

    Joined:
    20 Jun 2008
    Messages:
    258
    Likes Received:
    72
    Reputations:
    0
    надо создавать события OnKeyPress для каждого компонента Edit
     
    1 person likes this.
  6. blednii

    blednii Elder - Старейшина

    Joined:
    12 Jun 2007
    Messages:
    160
    Likes Received:
    23
    Reputations:
    -7
    И нельзя дать вписывать не цифры ибо это калькулятор, но не выходит цыфры продолжают работать.
     
  7. cremator (c)

    cremator (c) Elder - Старейшина

    Joined:
    20 Jun 2008
    Messages:
    258
    Likes Received:
    72
    Reputations:
    0
    что??? не понял вопрос
     
  8. blednii

    blednii Elder - Старейшина

    Joined:
    12 Jun 2007
    Messages:
    160
    Likes Received:
    23
    Reputations:
    -7
    1. Должны только цифры вписываться
    2. С проверкой помогли.



    А вот с цифрами всеравно никак не выходит.
     
  9. ProTeuS

    ProTeuS --

    Joined:
    26 Nov 2004
    Messages:
    1,239
    Likes Received:
    541
    Reputations:
    445
    юзай компонент дефольный SpinEdit. там уже решена проблема. вводится только цифры + контрорль границ ввода на уровне VCL там в пропертисах устанавливается
     
  10. cremator (c)

    cremator (c) Elder - Старейшина

    Joined:
    20 Jun 2008
    Messages:
    258
    Likes Received:
    72
    Reputations:
    0
    сделал так

    Code:
    procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    var i: integer; str:string;
    begin
      if (((Key = ord('V')) and (ssCtrl in Shift)) or ((Shift = []) and (Key = VK_INSERT))) then
      begin
       if Clipboard.HasFormat(CF_TEXT) then
       begin
        str:=clipboard.AsText;
        ClipBoard.Clear;
        for i:=1 to length(str) do
        begin
         case str[i] of #48..#57: clipboard.AsText:=clipboard.AsText+str[i];
        end;
        key := 0;
       end;
      end;
    end;
    
    end;
    
    
    procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
    begin
    if not(key in ['0'..'9',#27,#8]) then key:=#0;
    end;
    плюс в начале ещё uses ClipBrd;

    хотя если тебе не надо ловить числа из буфера то просто можно заменить этим
    Code:
     procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);   begin          ClipBoard.Clear;       end;
     
    #10 cremator (c), 2 Nov 2008
    Last edited: 2 Nov 2008
  11. ronald

    ronald Elder - Старейшина

    Joined:
    27 Mar 2008
    Messages:
    252
    Likes Received:
    41
    Reputations:
    6
    Просто перед ' ' попробуй поставить StrToInt
     
  12. blednii

    blednii Elder - Старейшина

    Joined:
    12 Jun 2007
    Messages:
    160
    Likes Received:
    23
    Reputations:
    -7
    Ronald, посмотри код, эта функция там и так используется.