VB.NET Dynamic Combobox Issues - Adding Items & Setting SelectedItem

I have a small application that users use to update information in AD. If the information has already been set, it should display the existing properties, and if not, give the user a drop down combobox to select from. This works fine as an English language application, with static text & options in the ComboBox. I'd now like to extend this as a mutli-language application (French, Italian, German & Spanish).
I'm using 'Thread.CurrentThread.CurrentCulture.Name' to get the OS language. Based on this, I then set the forms text labels & ComboBox options to one of the languages. i.e.
##Get language and set text variables to language
Private Function Language() As ADProperties
        Dim OSLanguage As String = Thread.CurrentThread.CurrentCulture.Name
        If OSLanguage = "en-GB" Then
            Language.SubmitBtn = "Submit"
            Language.ExitBtn = "Exit"
            Language.ComboQuestion1 = "Question 1"
            Language.ComboQuestion1 = "Question 2"
ElseIf OSLanguage = "it-IT" Then
            Language.SubmitBtn = "Confermare"
            Language.ExitBtn = "Esci"
            Language.ComboQuestion1 = "Questione 1"
            Language.ComboQuestion1 = "Questione 2"
End If

Open in new window

I then need to populate the ComboBox with these questions, currently I'm using:
##Populate ComboBox
Private Sub Q3ComboBox_MouseClick(sender As Object, e As MouseEventArgs) Handles Q3ComboBox.MouseClick
End Sub

Open in new window

However, the issue with this is that if you click on the combobox more than once, it re-add the options again, so if you have 10 options, the second click you get 20, then 3rd click 30. I've tried using ComboBox1.Items.Clear() above all the ComboBox1.Items.Add() options to remove them first, but it doesn't seem to work.

 Combobox Items Added Multiple Times
How can I build the ComboBox without the list growing on every click?

Once a user has entered their selection and submitted it, AD is updated with their selections (written to 'extensionAttribute3-10'). If a user re-runs the program it pulls this information back out and pre-fills the ComboBox using ComboBox.SelectedItem. When the user makes any changes, even to just a single combobox, and presses submit, it should re-submit all the information again. This worked fine when the ComboBoxes were static. However since using the dynamic ComboBoxes above, this no longer works, even though it displays the information pulled from AD as the selected option text, when you press submit, it pops up asking you to select an option from that ComboBox, so you have to click and select it again, so it's as if the Combobox.SelectedItem isn't being set correctly! So you can see in the attached pic, 'Security Question 1' is pre-filled with information pulled from AD. When I press submit, it doesn't recognise that there's a value. I've tried setting ComboBox1.ValueMember, ComboBox1.SelectedValue, ComboBox1.SelectedItem, ComboBox1.SelectedText

SelectedItems Not recognised
##Get information from AD and set variables
    Private Function GetUserProperties() As ADProperties
        Dim ADName As String = GetLogonName()
        Dim bSuccess As Boolean = False
        Dim dirEntry As DirectoryEntry = GetDirectoryEntry()
        Dim dirSearcher As DirectorySearcher = New DirectorySearcher(dirEntry)
        Dim waitTime As TimeSpan = New TimeSpan(0, 0, 0, 5, 0)
        dirSearcher.ClientTimeout = waitTime
        dirSearcher.Filter = ("(samAccountName=" & ADName & ")")
        dirSearcher.SearchScope = SearchScope.Subtree
            Dim dirResult As SearchResult = dirSearcher.FindOne()
            bSuccess = Not (dirResult Is Nothing)
            If dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value Is Nothing Then
                GetUserProperties.Three = "<Not Set>"
                GetUserProperties.Three = (dirResult.Properties("extensionAttribute3")(0).ToString())
            If dirResult.GetDirectoryEntry.Properties("extensionAttribute4").Value Is Nothing Then
                GetUserProperties.Four = "<Not Set>"
                GetUserProperties.Four = (dirResult.Properties("extensionAttribute4")(0).ToString())
            End If
            bSuccess = True
        Catch ex As Exception
            bSuccess = False
            MsgBox("No Connection to the domain.", MsgBoxStyle.Critical, "Network Error #1")
        End Try
    End Function

##Load Form
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
            currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
            Dim DisplayName As String = currentADUser.GivenName & " " & currentADUser.Surname
            Dim ADProp As ADProperties = GetUserProperties()
            ComboBox1.SelectedItem = ADProp.Three
            ComboBox2.SelectedItem = ADProp.Four
    End Sub

##Submit & Update
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim PIN As Integer
        Dim Q1 As String = Nothing
        Dim Q2 As String = Nothing
        ElseIf IsNothing(ComboBox1.SelectedItem) Then
            MsgBox("Please Select Security Question 1", MsgBoxStyle.Exclamation, "Invalid Question")
            Question1.ForeColor = Color.Red
        ElseIf IsNothing(ComboBox2.SelectedItem) Then
            MsgBox("Please Select Security Question 2", MsgBoxStyle.Exclamation, "Invalid Question")
            Question2.ForeColor = Color.Red
            Q1 = ComboBox1.Items(Q1ComboBox.SelectedIndex)
            Q2 = ComboBox2.Items(Q2ComboBox.SelectedIndex)
                Dim dirEntry As DirectoryEntry = GetDirectoryEntry()
                Dim dirSearcher As DirectorySearcher = New DirectorySearcher(dirEntry)
                dirSearcher.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" & ADName & "))"
                dirSearcher.SearchScope = SearchScope.Subtree
                Dim searchResults As SearchResult = dirSearcher.FindOne()
                If Not searchResults Is Nothing Then
                    Dim dirEntryResults As New DirectoryEntry(searchResults.Path)
                    SetADProperty(dirEntryResults, "extensionAttribute3", Q1)
                    SetADProperty(dirEntryResults, "extensionAttribute4", Q2)
                    MsgBox("PIN & Security Questions Successfully Set", MsgBoxStyle.OkOnly, "Success")
                    Form1_Load(Me, New System.EventArgs)
                End If
            End If
        End If
    End Sub

Open in new window

Who is Participating?

Duplicate entries in drop down

Well, first about the options duplicating, I think you are attaching handlers (can't be sure because there is not code for that) and might be firing the event multiple times for each click.  So the first handler is attached, one click produces one event and one set of results.  Second click creates a second event handler so that click produces two events which duplicates the results and so on.  This is just a guess, since the way you are adding the items means a .clear should sort out the problem (but it isn't).  Easiest way to check it to set a break point on where you are adding items and see if it gets hit more than once one the second click.

Single combo box change issue

By populating the combo boxes on click and simply setting the selected item the user actually hasn't selected anything so the selected item will be nothing, a quick work around would be to validate the corresponding AD value as well to see if it has a valid value.
if (IsNothing(ComboBox1.SelectedItem) And string.IsNullOrEmpty(ADProp.Three)) Then

Open in new window

Multiple languages

You are going about localizing your application the hard way.  There is an entire set of libraries and helpers built into .Net to help with this.  I am not saying your solution won't work, I'm sure it will, but there are easier ways to achieve the same results (with a lot less code).
Globalizing and Localizing .NET Framework Applications
Basically you create resource files for each language you intend to support (with a default for unsupported languages) and instead of assigning fixed strings to a button or label etc. you ask the framework for the resource by that name from the resource file.  It then determines what language is needed and retrieves the relevant resource from the resource file localized appropriately.  Later if you need to support another language all you have to do is create another resource file, no code will needed to be changed.
bjblackmoreAuthor Commented:
I've followed the instructions, and managed to get the form language translations to work. This works well for the form labels & comboboxes, and has fixed both the issues above (no need for mouse_click to load combobox) and the Combobox.SelectedItem.

However I've got MsgBox popups in some of the code, such as the 'Invalid Question' one in the picture above. Can I use the resource files to translate these - I couldn't see any way - or do I have to set variables following language detection using Thread.CurrentThread.CurrentCulture.Name as I was above?


  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Catch ex As Exception
            MsgBox("No Connection to domain." & Environment.NewLine & "Please connect to corporate network & try again.", MsgBoxStyle.Critical, "Network Error #2")
        End Try

        ElseIf IsNothing(ComboBox.SelectedItem) Then
            MsgBox("Please Select Security Question", MsgBoxStyle.Exclamation, "Invalid Question")

Open in new window

To put a *face* on what LordWabbit is saying.  I have attached a simple test project.

Testing screen shots -Initial load.Question 10 selected for security question 1, when showing the options for security question 2, option for Question 10 no longer shows.And so on.Clicking the Change Culture button changes the culture causing a refresh of the data in the drop downs to the selected culture.
bjblackmoreAuthor Commented:
Managed to get this working across 4 languages. Thanks
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.