Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
  Tip: Set a ComboBox Item at Startup  
 
 

Bill Hileman has this tip.

I recently answered a post in the microsoft.public.vb.controls newsgroup where I think this tip might be helpful for your readers. I poster asked how to set a combobox to the first item upon startup. MVP Ken Halter suggested the simple:

    ComboBoxName.ListIndex = 0

But warned that it would throw an error if the combobox was empty. I suggested:

    ComboBoxName.ListIndex = _
    (ComboBoxName.ListCount = 0)

Which sets the ListIndex property to zero if not empty (false) and -1 if empty (true).

One frequent poster replied that it used "evil type coercion" to which I agree, but another popular MVP, Randy Birch, stated he liked my solution.

I'm as against evil type coercion as the next guy, but I think boolean to integer and integer to boolean is not that big a deal, since they are basically the same, both being two bytes in size, and unsigned.


I would propose the following compromise:

    If ComboBoxName.ListCount = 0 Then
        ComboBoxName.ListIndex = -1
    Else
        ComboBoxName.ListIndex = 0
    End If

The first version might break if Microsoft ever decides to be consistent about whether Collections start with index 0 or 1. It would definitely break if they changes the values of True and False. Not as simple but a little easier to understand.

 

Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated