Link to home
Start Free TrialLog in
Avatar of NickRackham
NickRackham

asked on

In a muddle with "if" statements

I'm using a form with 4 edit boxes and a button. When I click the button I want to check that all 4 edit boxes have been filled and if not then to have a dialog box pop up to say "please complete edit box *" and to return the focus to the empty edit box.

I'm trying to use nested if staements but I'm getting in a muddle.

Many thanks

Nick
Avatar of rwilson032697
rwilson032697

Do it like this:

Function CheckEdit(Edit : TEDit):Boolean;
begin
  Result := Edit.Text <> '';
  if not result then
    begin
      ShowMessage('Please fill in '+edit.name');
      SetFocus(Edit.Handle);
    end;
end;


  if CheckEdit(Edit1) and
     CheckEdit(Edit2) and
     CheckEdit(Edit3) and
     CheckEdit(Edit4) then
    begin
      // All values OK
    end;

Cheers,

Raymond.
Avatar of NickRackham

ASKER

Raymond,

I should have mentioned in my question that I'm only just starting to learn Delphi. (like in the last few weeks!!)

This is for a college project.

The code I'm using:-

procedure TTankerFrm.CreateTankerBtnClick(Sender: TObject);
       {This procedure checks to make sure that all of the edit
        boxes have been completed and if not, returns the focus to
        the empty field for completion prior to posting the data to
        the Shipment Details frame.
        }
       begin
            if name.text  = '' then;
            MessageDlg('Please complete the Name field', mtConfirmation, [mbOK], 0);

            if RegNo.text = '' then
            MessageDlg('Please complete the Registration Number field', mtConfirmation, [mbOK], 0);

            if Capacity.text = '' then
            MessageDlg('Please complete the Capacity field', mtConfirmation, [mbOK], 0);

            if CurrLocation.text = '' then
            MessageDlg('Please complete the Current Location field', mtConfirmation, [mbOK], 0);

            if BallastRequired.text = '' then
            MessageDlg('Please complete the Ballast Required field', mtConfirmation, [mbOK], 0);
       end;

I would like to use nested if statements so that I can follow through with my tutor what I'm trying to achieve.

Can you tell me where to correct my code please.

Many thanks

Nick

PS Off to catch some zzzzzz' so I'll pick this up in the morning.
I would change your code like this (to use else's):

begin
if name.text  = '' then;
  MessageDlg('Please complete the Name field', mtConfirmation, [mbOK], 0)
else
  if RegNo.text = '' then
    MessageDlg('Please complete the Registration Number field', mtConfirmation, [mbOK], 0)
  else
    if Capacity.text = '' then
      MessageDlg('Please complete the Capacity field', mtConfirmation, [mbOK], 0)
    else
      if CurrLocation.text = '' then
        MessageDlg('Please complete the Current Location field', mtConfirmation, [mbOK], 0)
      else
        if BallastRequired.text = '' then
          MessageDlg('Please complete the Ballast Required field', mtConfirmation, [mbOK], 0)

Cheers,

Raymond.

       
This is even less work...

procedure TForm1.FormCreate(Sender: TObject);
begin
 Edit1.tag:=Longint(pchar('please enter a name'));
 Edit2.tag:=Longint(pchar(' please enter an address'));
 Edit3.tag:=Longint(pchar(' please enter an age'));

end;

procedure TForm1.Button1Click(Sender: TObject);
var loopint:integer;
begin
    For Loopint:=0 to Form1.controlcount-1 do
    begin
      if (Controls[loopint] is Tedit) then
      begin
        if (Controls[loopint] as Tedit).text='' then
        begin
          Showmessage(Pchar(Longint((Controls[loopint]as Tedit).tag)));
          (Controls[loopint] as Tedit).SetFocus;
          //exit;
        end;
      end;
    end;
end;


Good luck!!
DrDelphi: I think posting that as an answer was a little unwarranted. Furthermore, aside from the clear attachment of constant strings to the tag property (btw, this approach can bite you in other situations), looping through all edit controls on the form may not be beneficial!

Cheers,

Raymond.
Raymond,
  I agree insomuch as posting as an answer was not right... it was not done deliberately. As for the tag property cusing a problem, I disagree wholeheartedly, since the property can be assigned different values at runtime making the routine I gave very versatile. All of which of course is a moot point. The real issue is whether or not it will work for Nick.


Good luck!!
-DrDelphi
DrDelphi changed the proposed answer to a comment
The tag usage is not a problem - agreed, but consider this code (an actual example from one of our apps!):

var
  Buffer : Array[1..1000] of char;
  P : PChar;

begin
  P := @Buffer;
....
  P := 'Fred';
....
  StrCat(P, 'Boom!');
end;

Cheers,

Raymond.
Afraid I don't see the point....
You get an AV on the StrCat line...

I was just trying to illustrate an issue with treating literal strings as PChars in terms of assignment etc.

Cheers,

Raymond.
Still don't see the point...First off, I do not get an Acess Violation on the strCat line in version 3 or 4. In 5 I do, but it is easily averted like this:

var
  Buffer : array [0..1000] of char;

begin
  Buffer:='Fred';
  StrCat(Buffer, PCHAR('Boom!'));
  ShowMessage(Buffer);
end;



Precisely! (ie: you do get it).

In D5 they have obviously 'optimised' assignment of literals to PChars (and in strings we have noticed in a separate, but similar situation) by setting the PChar to point to the memory containing the constant.

Cheers,

Raymond.

PS: Does string assignment to an array like you have done place a #0 at the end of the string?
Scenario:
Buffer:array [0..1000] of char;

D3:
  Inttostr(Ord(Buffer[length(Buffer)]=0

D4: same as D3


D5:
  I needed to either look at length(Buffer)-1 OR length(Strpas(Buffer[length(buffer)]

in all cases, yes, a #0 is added to the end of the buffer. This is due to the String datatype defaulting to Ansistring in D32 ( I believe, but I have not found it in the help files yet... still looking)

-DrDelphi


 
this is Raymond - code in your example ... this is the right way

DrDelphi - I think your code is ok - but If you look at it nobody knows want this code does ...

procedure TTankerFrm. CreateTankerBtnClick (Sender: TObject);
Function CheckEdit(Edit : TEDit; sMsg : string):Boolean;
begin
  Result := Edit.Text <> '';
  if not result then
    begin
      ShowMessage(sMsg);
      SetFocus(Edit.Handle);
    end;
end;

begin
  if CheckEdit(Edit1,('Please complete the Name field') and
     CheckEdit(Edit2,'...') and
     CheckEdit(Edit3,'...') and
     CheckEdit(Edit4,'...') then
    begin
      // All values OK
    end;
end;
please don't worry
I understand your code
I'm a proud owner of BP7.0, Turbo Pascal for Windows 1.5, D1234. I know what a Pointer is good for - but I gain experience that beginners don't understand why I need a pointer.
I think you can do these 4 tests without pointers....

(and now something completly different)
there is a
function setlength(string,integer)
(i don't know if there is a change in d5-strings)
and for most API-call it is very usefull

var s:string;
    i:integer
begin
 setLength(s,256);
 i := GetWindowTitle(handler,pchar(s),256);
 setLength(s,i);
end;

I mean that GetWindowTitle need a window handler and a buffer for the string and the size of the buffer and the the result is the real length of the string.
 (may be I wrong with GetWindowTitle, but many API work this way)

So don't worry DrDelphi and Rwilson ... if we meet we do drinking beer and discuss these (the first round is mine :-)

Flori
floriangrimm,
 Hmmmm... I'm not so sure that your characterization of "nobody knowing" what my code does is accurate.Rwilson obviously does... as do I.  
Hi all,

Wow - can I join in too :o) Looks like it's been busy!! Well as you've all been posting while I was asleep (and then at work) I'll start of with Raymond's next comment. This works great except that (as an example) if the Capacity field is not filled in the dialog box appears, click OK but the cursor doesn't move back to the capacity box? How do I do this. I'm OK with the if - else statemaents (kinda like vba - or is that like swearing in this topic area?).

DrDelphi and Raymond's next comments. You're losing me completely <totally confused> Don't forget that I'm a beginner - within the last two weeks or so, and that my programming skills are extremely basic.

floriangrimm - not sure what your code is meant to do except that it looks like you've posted Raymonds code as an answer!! Am I right? Sorry but as mentioned above I'm a complete novice and it all looks double dutch to me. This isn't meant to be derogatory but I just don't understand.

I think I'll stick with Raymonds code with the additional question - how do I get the cursor back to the offending blank edit box. It's not that the other code doesn't work - more like if I don't understand it and it's above the level that's expected of me then I feel as though I'm cheating. Hope that makes sense.

Many thanks

Nick

Hello all,

While browsing the topic area, I happened to read this thread.

floriangrimm: Hello and welcome to Experts Exchange. With regards to the answer you posted, I'd like to caution you about taking a previous comment and reposting it as an answer. Do Not Do That! No Expert appreciates it and it can only cause problems. Consider how you would feel if you posted a comment on a question and another Expert reposted as an answer and got credit for answering the question. Perhaps you will say that that would be no problem for you. I can appreciate that. I would request that you respect the fact that it probably is not okay with most Experts and refrain from doing so out of professional courtesy.

If you think that a previous comment answered the question, then you can post a comment saying that you concur with the previous comment and it is the correct answer. If you feel that the previous comment is on the right track but not the right answer, you can post your new and original idea as the answer.

darinw
Customer Service
Nick: I got confused over setfocus, instead of saying:

Setfocus(edit1.handle);

you should call the setfocus method of the control itself, like this:

edit1.setfocus; { This is how we do it in our apps)

Cheers,

Raymond.
Raymond, Could you expand a bit on your last comment. It's late - I'm tired and Delphi is a complete new ballgame for me :o)

Many thanks.

Nick

PS DarinW - Couldn't have put it better myself. :o)
Raymond, I'm using the code you posted :-


________________________________________
I would change your code like this (to use else's):

begin
if name.text  = '' then;
  MessageDlg('Please complete the Name field', mtConfirmation, [mbOK], 0)
else
  if RegNo.text = '' then
    MessageDlg('Please complete the Registration Number field', mtConfirmation, [mbOK], 0)
  else
    if Capacity.text = '' then
      MessageDlg('Please complete the Capacity field', mtConfirmation, [mbOK], 0)
    else
      if CurrLocation.text = '' then
        MessageDlg('Please complete the Current Location field', mtConfirmation, [mbOK], 0)
      else
        if BallastRequired.text = '' then
          MessageDlg('Please complete the Ballast Required field', mtConfirmation, [mbOK], 0)

Cheers,

Raymond.
________________________________________

Cheers

Nick

       

Adjusted points from 50 to 100
ASKER CERTIFIED SOLUTION
Avatar of rwilson032697
rwilson032697

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try this:

.....
type
  TEditMsg= record
    EditBox: TEdit;
    Msg: String;
   end;

procedure CheckEdits;
var
 a: array[1..4] of TEditMsg;
 index: integer;
begin
 a[1].EditBox:= Edit1;
 a[1].Msg:= 'Please fill in name...';
 ...
 for index:= 1 to 4 do
 if (a[index].EditBox.Text = '')
   ShowMessage(a[index].msg);
 ...
end;
   
A little more coding, but only one if statement and very readable code...
Sorry, missed the focus part. Use something like this:

a[index].EditBox.SetFocus;
QUOTE:
_______________________________________
Sorry but as mentioned above I'm a complete novice and it all looks double dutch to me.
_______________________________________

Okay, I take offense here; I happen to BE Dutch! :-)

Anyway, I don't know what everyone's still doing here, since the question has obviously already been answered.
Raymond, Many thanks. If I have the time to try and understand your first comment i.e. wrap it all up in a procedure then I'll give it a go - but until then I've got to work hard on completing this project, and I can explain the if else statements - it's just the syntax that I'm having trouble with.

Dentener, many thanks for the comments but I don't understand Delphi well enough at present to delve nto something that is going to take time away from finishing this college project.

nrico, apologies - no offence was intended - besides the grass is always smoother in Holland!! :o)