Artur Alvaro
Artur Alvaro

Reputation: 115

Why does this Visual Basic code work?

What it basically does is checks if the user input is already in ComboBox1. If it is, alerts the user. If not, it adds it to the combobox

The thing I don't get is the "For Each StringIterador In ComboBox1.Items loop". How could an Item object be placed in a String variable? I know Strings are objects but... You can't just place a random object into a String variable, can you? Also the String is later used as an Item object back "ComboBox1.GetItemText(StringIterador)"

Private Sub ComboBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ComboBox1.KeyPress
    Dim StringIterador As String
    If e.KeyChar = ControlChars.Cr Then
        If ComboBox1.Text <> "" Then
            For Each StringIterador In ComboBox1.Items
                If ComboBox1.GetItemText(StringIterador).Equals(ComboBox1.Text) Then
                    MsgBox("ya está en la lista")
                    Exit Sub
                Else
                    ComboBox1.Items.Add(ComboBox1.Text)
                    Exit Sub
                End If
            Next
        End If
    End If
End Sub

Upvotes: 1

Views: 64

Answers (1)

christutty
christutty

Reputation: 952

The documentation for the For Next statement (https://msdn.microsoft.com/en-us/library/5ebk1751.aspx) requires that "The data type of element must be such that the data type of the elements of group can be converted to it." so this code will work as long as each item can be converted to string. It's not storing the item object in a string, it's converting the item to a string and storing that.

I haven't tested this but I suspect that if you stored an object in Items that couldn't be converted to string a run-time exception would be raised. Of course since the code is adding ComboBox1.Text each time this code will only add text items and therefore won't set up a situation in which the string conversion would be invalid.

In the same way GetItemText() is documented as "If the DisplayMember property is not specified, the value returned by GetItemText is the value of the item's ToString method. Otherwise, the method returns the string value of the member specified in the DisplayMember property for the object specified in the item parameter." so, again, it's probably working because the objects added will return a string. If you added a complex object to the combobox you'd probably see the object's type displayed (which, from memory) is the fallback result of ToString().

Upvotes: 2

Related Questions