TheSwamp
Code Red => VB(A) => Topic started by: MP on April 13, 2005, 07:40:56 PM
-
In VB(A) one frequently simplifies one's code by using the "With" statement to eliminate redundant object references and/or make code more maintainable.
Instead of --
myObject.Method1 parameters
myObject.Method2 parameters
You might do this --
With myObject
.Method1 parameters
.Method2 parameters
End With
Thank you Michael, been doing that for years, move on son.
Hang on a sec.
What you might not realize is that you can use the "With" statement with any expression that returns an object or type.
Eh?
Ok, a quick, but real example. Say you're adding items to a listview object and each entry has sub items. Here's a typical approach --
Dim Item As ListItem
Set Item = listview1.ListItems.Add(, , "Item")
Item.SubItems(1) = "Detail 1"
Item.SubItems(2) = "Detail 2"
Which can be simplified to (and frequently is) --
Dim Item As ListItem
Set Item = listview1.ListItems.Add(, , "Item")
With Item
.SubItems(1) = "Detail 1"
.SubItems(2) = "Detail 2"
End With
But what about --
With listview1.ListItems.Add(, , "Item")
.SubItems(1) = "Detail 1"
.SubItems(2) = "Detail 2"
End With
:cheesy:
-
This is the kind of tip that will allow good programmers to become great....
-
Good tip. I use "with" whenever I can as I'm lazy and don't like to type. Also it produces nicer looking code.
-
Thanks guys, wasn't sure if it would be useful for or not but that apparently couldn't stop me from posting it. This of course has never happened to me before.
:)
-
And going further:
With MyGrid
Set .DataSource = MyRecSet
With .Columns(1)
.Caption = "Cap1"
.Width = 100
.AllowSizing = False
.Locked = True
End With
With .Columns(2)
.Caption = "Cap2"
.Width = 200
.AllowSizing = False
.Locked = True
End With
'...
End With
Cheers
-
Good stuff Jürg, thanks.
(http://www.theswamp.org/screens/mp/thumbsup.gif)
-
Glad to contribute... :D
Cheers
-
You have a lot to contribute Jürg, hope we see you here frequently.
:cheesy:
-
Probably yes, but my greatest problem is to find enough time to scan/read all the threads in this forum. Maybe 'cause I'm not (yet) familiar with web based groups like TheSwamp. :(
Cheers
-
One tip for you...
Create a Bookmark / Favourite and give it this address:
http://www.theswamp.org/phpBB2/search.php?search_id=newposts&sid=47b0892991d610d7b8377df9ea3906a0
(View posts since last visit)
-
One tip for you...
Create a Bookmark / Favourite and give it this address:
Thx, that was it...
Cheers