ComboBox Items

CJLeit

Freshman
Joined
Feb 1, 2006
Messages
32
I have a combo box that I want to loop through all of the items in it and if the string returned from a function is in the list items I want to set the text to that string. I found a way to do it but it seems like there must be a better way to do it. Here is the way I'm currently doing it. Head is the string returned from my function. Any suggestions?

Code:
For Each row As System.Data.DataRowView In cboHead.Items
    If (row.Row.Item(0).ToString) = head Then
        cboHeadead.Text = head
        Exit For
    End If
Next
 
If you just want a single string in the combo, and not a DataRowView, you could use the ComboBox's IndexOf method using your variable "head".

If you have the original DataView you used to populate the drop-down then you might be able to use it's FindRows method to get a DataRowView array. Assuming your filter would get you exactly one row, you could use that in the ComboBox's IndexOf method. For example (my VB is rusty):
Visual Basic:
Dim dv as DataView ' Assume set earlier
'...

' Here is the filter, to find matching rows
Dim matchingItems As DataRowView() = dv.FindRows(head)
If matchingItems.Length > 1 Then
    cboHead.SelectedIndex = cboHead.IndexOf(matchingItems(0))
End If

-ner
 
Call me a nit picker but I would assign "head" to a variable outside the look and reference to it, preferably at the beginning of your method.

I hate to absolutely hardcode something like that inside a loop, especially when the loop is much larger, you never know when you'll need to change it and imho defining the target string is best put at the top of the method.
 
Back
Top