Solved

In a muddle with "if" statements

Posted on 2000-04-16
27
245 Views
Last Modified: 2010-04-04
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
0
Comment
Question by:NickRackham
  • 8
  • 7
  • 6
  • +4
27 Comments
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2721161
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.
0
 
LVL 4

Author Comment

by:NickRackham
ID: 2721179
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.
0
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2721207
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.

       
0
 
LVL 6

Expert Comment

by:DrDelphi
ID: 2721380
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!!
0
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2721395
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.
0
 
LVL 6

Expert Comment

by:DrDelphi
ID: 2721404
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
0
 
LVL 6

Expert Comment

by:DrDelphi
ID: 2721406
DrDelphi changed the proposed answer to a comment
0
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2721420
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.
0
 
LVL 6

Expert Comment

by:DrDelphi
ID: 2721439
Afraid I don't see the point....
0
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2721449
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.
0
 
LVL 6

Expert Comment

by:DrDelphi
ID: 2721466
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;



0
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2721477
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?
0
 
LVL 6

Expert Comment

by:DrDelphi
ID: 2721532
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


 
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Expert Comment

by:floriangrimm
ID: 2721745
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;
0
 

Expert Comment

by:floriangrimm
ID: 2722483
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
0
 
LVL 6

Expert Comment

by:DrDelphi
ID: 2722370
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.  
0
 
LVL 4

Author Comment

by:NickRackham
ID: 2724246
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

0
 
LVL 3

Expert Comment

by:darinw
ID: 2724463
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
0
 
LVL 12

Expert Comment

by:rwilson032697
ID: 2724550
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.
0
 
LVL 4

Author Comment

by:NickRackham
ID: 2724579
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)
0
 
LVL 4

Author Comment

by:NickRackham
ID: 2724588
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

       

0
 
LVL 4

Author Comment

by:NickRackham
ID: 2724589
Adjusted points from 50 to 100
0
 
LVL 12

Accepted Solution

by:
rwilson032697 earned 100 total points
ID: 2724613
OK - Doing it the long hand way, using nested elses, you would need to do this for each check:

if name.text  = '' then
  begin
    MessageDlg('Please complete the Name field', mtConfirmation, [mbOK], 0);
    name.setfocus;
  end
else
  if RegNo.text = '' then
    begin
      ...
    end
  else
     ... and so on

Usually you would wrap the check, message display and set focus call in a little procedure to tidy it up, much like my initial answer.

Does that clear things up?

Cheers,

Raymond.
0
 

Expert Comment

by:dentener
ID: 2726051
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...
0
 

Expert Comment

by:dentener
ID: 2726058
Sorry, missed the focus part. Use something like this:

a[index].EditBox.SetFocus;
0
 
LVL 1

Expert Comment

by:nrico
ID: 2726162
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.
0
 
LVL 4

Author Comment

by:NickRackham
ID: 2728108
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)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now