Logo

Hacker’s Guide to Visual FoxPro
An irreverent look at how Visual FoxPro really works. Tells you the inside scoop on every command, function, property, event and method of Visual FoxPro.

WITH ... ENDWITH

This command doesn’t let you do anything new. It just makes it easier to refer to a bunch of properties of the same object.

Usage

WITH oObject
   [ Statements ]
ENDWITH

It can be pretty tedious to assign new values to a bunch of properties. Say you’re working on a check box embedded in a grid, which in turn is embedded in a page of a page frame, but you’re doing the manipulation at the form level. To change its caption, you’d need something like:

ThisForm.pgfMyFrame.pagPage1.grdMyGrid.grcColumn1.chkMyCheck.Caption="Wowza!"

Imagine changing eight or 10 properties this way. WITH is a better way. You write all that out once and then Visual FoxPro understands what you mean:

WITH ThisForm.pgfMyFrame.pagPage1.grdMyGrid.grcColumn1.chkMyCheck
    * manipulate as many properties as you want
    .Caption="Wowza!"
    .Enabled=.T.
    .Value=.T.
ENDWITH

In our tests here at Hacker’s Labs, we found that using the WITH version was also slightly faster than the long form. The difference isn’t enough to matter in most situations, but might be handy when you’re trying to squeeze that last little bit of performance out of your app. Keep in mind, too, that the more properties you’re setting, the more improvement you get.

You might think the only statements you can put inside the WITH would be property assignments and that each line must begin with the “.” to set off the property, but you’d be wrong. In fact, pretty much any command can go in there. Not only that, but you can refer to properties anywhere in the command line without prefacing them with the object name. Both stand-alone and end-line comments (with &&) are permitted. Finally, you can nest WITH statements so that inside a WITH, you can add another level or two of referencing and speak directly to a lower-level object.

Note that we said “you can” do all those things. That doesn’t mean you should. It wouldn’t take much to end up with an unreadable mess. We think WITH is pretty good for what it’s intended for, letting you cut down on complicated references. But, mixing a lot of other code in with this isn’t a good idea. Remember, overly clever code leads to support calls.

Example

frmMyForm=CREATEOBJECT("Form")
* code like this is an okay idea
WITH frmMyForm
   .Height = 200
   .Width = 100
   .Caption = "Form to demonstrate WITH command"
ENDWITH

* code like the following is a not-so-great idea
WITH frmMyForm
   .Show()
   .AddObject("txtMyText","textbox")
   WITH .txtMyText
      .Height = .Parent.Height/10
      .Width = .Parent.Width/2
      .Visible = .T.
   ENDWITH
ENDWITH