Solved

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

Posted on 2014-12-12
4
475 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 34

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

623 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