Solved

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

Posted on 2014-12-12
4
408 Views
Last Modified: 2014-12-19
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
ComboBox1.Items.Add(Language.ComboQuestion1)
ComboBox1.Items.Add(Language.ComboQuestion2)
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.PropertiesToLoad.Add("extensionAttribute3")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute4")
        dirSearcher.SearchScope = SearchScope.Subtree
        Try
            Dim dirResult As SearchResult = dirSearcher.FindOne()
            bSuccess = Not (dirResult Is Nothing)
            If dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value Is Nothing Then
                GetUserProperties.Three = "<Not Set>"
            Else
                GetUserProperties.Three = (dirResult.Properties("extensionAttribute3")(0).ToString())
            If dirResult.GetDirectoryEntry.Properties("extensionAttribute4").Value Is Nothing Then
                GetUserProperties.Four = "<Not Set>"
            Else
                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")
            Application.Exit()
        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
         Else
            Q1 = ComboBox1.Items(Q1ComboBox.SelectedIndex)
            Q2 = ComboBox2.Items(Q2ComboBox.SelectedIndex)
            Else
                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)
                    dirEntryResults.CommitChanges()
                    dirEntryResults.Close()
                    MsgBox("PIN & Security Questions Successfully Set", MsgBoxStyle.OkOnly, "Success")
                    Form1_Load(Me, New System.EventArgs)
                End If
                dirEntry.Close()
            End If
        End If
    End Sub

Open in new window

0
Comment
Question by:bjblackmore
  • 2
4 Comments
 
LVL 11

Accepted Solution

by:
LordWabbit earned 350 total points
ID: 40496758

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.
0
 

Author Comment

by:bjblackmore
ID: 40497287
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?

i.e.

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

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

Open in new window

0
 
LVL 32

Assisted Solution

by:it_saige
it_saige earned 150 total points
ID: 40497300
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.
-saige-
EE-Q28579851.zip
0
 

Author Closing Comment

by:bjblackmore
ID: 40508853
Managed to get this working across 4 languages. Thanks
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now