Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Combobox won't populate, need help with current code.

Posted on 2016-09-22
14
Medium Priority
?
52 Views
Last Modified: 2016-09-23
I'm currently working on a windows form application in VS2015 using the visual basic language. I recently got some feedback from end users and the majority did not like having a listbox on the form, they preferred a dropdown combobox. The Previous set up was a textbox to filter the data in the listbox. Now the combobox is used to search for the information and show a list as items are typed into the combobox.

I do know that the listbox control and the combobox control are very similar in how they work.

Here is what I have so far, let me know if I missed anything as I'm just listing the code from the project that includes data for the combobox. The rest of the code is irrelevant, Except for the Global Variable Class "GVar". I know there is a lot of code here  just not sure what is causing my issue.

Imports System.IO
Imports System.Data.SqlClient
Imports MyPDFActiveX

Public Class frmCPS
    Private Sub frmCPS_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Focus()
        BringToFront()
        Show()
        Me.DoubleBuffered = True
        Dim cnStr As String
        cnStr = "Server=FMSERVER\EXTRAS;Database=eco;User ID=ForestGump;Password=Jenny"
        GVar.DBCon = New SqlConnection(cnStr)
        GVar.DBCon.Open()

        cbPartNum.Focus()
        If Not Directory.Exists(GVar.SourceFolder) Then Throw New Exception("Folder doesn't exist, OMG! What happened to our files")

        BuildDataTable()

        If Directory.Exists(GVar.DWFtf) = False Then Directory.CreateDirectory(GVar.DWFtf)
    End Sub

    Public Sub BuildDataTable()
        Try
            Dim extenions = New String() {".pdf"}
            Dim dirInfo = New System.IO.DirectoryInfo(GVar.SourceFolder)
            Dim files = dirInfo _
            .EnumerateFiles("*", System.IO.SearchOption.AllDirectories) _
            .Where(Function(f) extenions.Contains(f.Extension.ToLower))

            Dim _dtPDFfiles As New DataTable()
            _dtPDFfiles.Columns.Add("FullPath")
            _dtPDFfiles.Columns.Add("FileNameWe")

            If GVar.currentFilter <> "" Then
                For Each file In files
                    If file.Name.ToUpper Like GVar.currentFilter + "*" Then
                        Dim name = file.Name
                        Dim pos = name.IndexOf(".")
                        name = name.Substring(0, pos)
                        _dtPDFfiles.Rows.Add(New Object() {file.FullName, name})
                    End If
                Next
            End If
            With cbPartNum
                .DataSource = _dtPDFfiles
                .ValueMember = "FullPath"
                .DisplayMember = "FileNameWe"
                .DroppedDown = True
                .Update()
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub cbPartNum_TextChanged(sender As Object, e As EventArgs) Handles cbPartNum.TextChanged
        Timer1.Interval = 5000 'ms
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Stop()
        GVar.currentFilter = cbPartNum.Text
        BuildDataTable()
    End Sub

    Private Sub cbPartNum_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles cbPartNum.MouseDoubleClick
        'This Sub-Routine opens the selected file in the cbPartNum combobox when the mouse button is double clicked
        LoadThePDF()
    End Sub

    Private Sub cbPartNum_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cbPartNum.KeyDown
        'This Sub-Routine opens the selected file in the cbPartNum combobox when the enter key is pressed down
        Dim theFile = cbPartNum.SelectedValue
        If e.KeyCode = Keys.Enter Then
            LoadThePDF()
        End If
    End Sub

    Private Sub cbPartNum_SelectedValueChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbPartNum.SelectedValueChanged
        Dim fp As DataRowView = cbPartNum.SelectedItem
        If cbPartNum.SelectedIndex <> -1 Then
            MessageBox.Show(fp.Row("FileNameWe"))  'this line of code is for testing purposes, delete before publishing finished application.
            cbPartNum.Text = (fp.Row("FileNameWe"))
        End If
    End Sub

    Private Sub LoadThePDF()
        'This Sub-Routine loads the pdf file in the pdf ActiveX control window, it also removes any pdf file in the temp folder before opening the file.
        'there is error control for not typing in the correct part number too, this stops the program from crashing when a non existing part number is typed in.
        My_PDF_AX1.OpenFile("", "")
        My_PDF_AX1.ShowNavigationPanels(True)
        My_PDF_AX1.ShowNavPanelByString("Pages")

        If (File.Exists(GVar.currentTempFile)) Then
            File.SetAttributes(GVar.currentTempFile, FileAttributes.Normal)
            File.Delete(GVar.currentTempFile)
        End If

        Dim theFile As String = cbPartNum.SelectedValue

        If theFile Is Nothing Then
            MessageBox.Show("ATTENTION " & GVar._UserName & ": You just FAT Fingered the part number try again", "ERROR: WRONG FILE NAME")
            cbPartNum.Focus()
            Exit Sub
        End If

        GVar.currentTempFile = Path.GetTempPath + Path.GetFileName(theFile)
        File.Copy(theFile, GVar.currentTempFile, True)

        My_PDF_AX1.OpenFile(GVar.currentTempFile, "")
        My_PDF_AX1.ShowNavigationPanels(True)
        My_PDF_AX1.ShowNavPanelByString("Pages")
        My_PDF_AX1.ZoomLevel = 1
        My_PDF_AX1.ShowToolBar(True)
        My_PDF_AX1.ShowTitleBar(False)

    End Sub

Open in new window

0
Comment
Question by:Steve Williams
[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
  • 8
  • 6
14 Comments
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41810684
if you place a breakpoint on row 42, does it stop?
0
 
LVL 1

Author Comment

by:Steve Williams
ID: 41810784
Eric, It does not stop when placing a breakpoint at code line 42!
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41810789
This means that you have no file to show up in the combo.

is GVar.currentFilter empty?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:Steve Williams
ID: 41810810
Eric I added a messagebox just below line 42 and this is what I get!

 MessageBox.Show(GVar.currentFilter, "Notification")

Open in new window


I then run the app in debug mode frmCPS form opens. Then I typed "part-0001" into the combo box and the messagebox returned the same so it is not equal to ""
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41810830
Really strange. Can you try replacing this line (42):
_dtPDFfiles.Rows.Add(New Object() {file.FullName, name})

Open in new window



with:
Dim dtrNewRow As DataRow = _dtPDFfiles.NewRow
dtrNewRow("FullPath") = file.FullName
dtrNewRow("FileNameWe") = name
_dtPDFfiles.Rows.Add(dtrNewRow)

Open in new window

0
 
LVL 1

Author Comment

by:Steve Williams
ID: 41810943
Eric, I changed the code as you requested and it made no difference. Running the code has the same end result.

Also noticed that when I'm done typing in the part number the cursor goes from the end of the typed in text back to the home position. And If I hit enter the text that I just typed in disappears.
0
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 2000 total points
ID: 41810952
could you please remove all the code that is not related to loading the combo? I see that you have a timer that reloads the combo after textchanged and many other events.

Start by loading your combo and work from there!
0
 
LVL 1

Author Comment

by:Steve Williams
ID: 41811034
Ok thanks Eric, appreciate your help!
0
 
LVL 1

Author Comment

by:Steve Williams
ID: 41811375
OK Eric, I did as you suggested and started over the code looks all different now.  But it is working and populating the combo box. Now I just have to add a filter so when I type in the targeted part number it narrows the list to what is available in the table.

Here is the current updated code

    Public Sub BuildDataTable()
        Dim _dt As DataTable = New DataTable("Found_PDF_Files")
        _dt.Columns.Add("FullPath")
        _dt.Columns.Add("FileName")
        Dim ext_pdf As String = ".pdf"
        For Each _file In Directory.GetFiles(GVar.SourceFolder)
            Dim theFile = Path.GetFileName(_file)
            If theFile.Contains(ext_pdf) Then
                Dim _dr As DataRow = _dt.NewRow
                _dr("FullPath") = _file
                _dr("FileName") = (theFile.Substring(0, theFile.Length - 4)).ToString.ToUpper
                _dt.Rows.Add(_dr)
            End If
        Next
        Try
            With cbPartNum
                .DataSource = _dt
                .DisplayMember = "FileName"
                .ValueMember = "FullPath"
                .DroppedDown = True
            End With
        Catch ex As Exception
            MsgBox(“Unable to Fill the Combobox:” & cbPartNum.Name & ” with values” & “:” & Err.Description)
        End Try
    End Sub

    Private Sub cbPartNum_TextChanged(sender As Object, e As EventArgs) Handles cbPartNum.TextChanged
        Timer1.Interval = 500000000 'ms
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Stop()
        BuildDataTable()
    End Sub

Open in new window

0
 
LVL 70

Assisted Solution

by:Éric Moreau
Éric Moreau earned 2000 total points
ID: 41811394
maybe the combo box is not appropriate for what you are trying to do. Are you aware of the Autocomplete feature of the textbox: http://emoreau.com/Entries/Articles/2012/04/A-more-useful-auto-complete-Textbox-control.aspx
0
 
LVL 1

Author Closing Comment

by:Steve Williams
ID: 41811416
Eric I'm considering this question answered, I have way more than I asked for and it will probably take me a day or so to finish this portion of my code and to make sure it works correctly. I will post an update once I have finished. Thanks for all your help!
0
 
LVL 1

Author Comment

by:Steve Williams
ID: 41812377
I have switched over to the Autocomplete textbox. There are pro's and cons but I think the pro's outweigh the con's. Here is the Code I used. It's actually quite responsive for having 6100 + files to sift thru.

 Public Sub BuildDataTable()
        Dim _dt As DataTable = New DataTable("Found_PDF_Files")
        _dt.Columns.Add("FullPath")
        _dt.Columns.Add("FileName")

        Dim _ds As DataSet = New DataSet("MyCollection")
        _ds.Tables.Add(_dt)

        Dim ext_pdf As String = ".pdf"
        For Each _file In Directory.GetFiles(GVar.SourceFolder)
            Dim theFile = Path.GetFileName(_file)
            If theFile.Contains(ext_pdf) Then
                Dim _dr As DataRow = _dt.NewRow
                _dr("FullPath") = _file
                _dr("FileName") = (theFile.Substring(0, theFile.Length - 4)).ToString.ToUpper
                _dt.Rows.Add(_dr)
            End If
        Next

        Try
            Dim result = From o In _dt.AsEnumerable() Select o.Field(Of String)("FileName")
            Dim values() As String = result.ToArray()
            txtPartNum.AutoCompleteSource = AutoCompleteSource.CustomSource
            txtPartNum.AutoCompleteCustomSource.AddRange(values)
        Catch ex As Exception
               MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub txtPartNum_TextChanged(sender As Object, e As EventArgs) Handles txtPartNum.TextChanged
        Timer1.Interval = 15000 'ms
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Stop()
        BuildDataTable()
    End Sub

    Private Sub txtPartNum_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles txtPartNum.MouseDoubleClick
        LoadThePDF()
    End Sub

    Private Sub txtPartNum_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPartNum.KeyDown
        Dim theFile = txtPartNum.SelectedText
        If e.KeyCode = Keys.Enter Then
            LoadThePDF()
        End If
    End Sub

Open in new window


One of the differences between the text box and combobox / listbox controls is that the autocomplete textbox does not have the DisplayMember or ValueMember properties. So once I overcome this obstacle I was good to go. The way I got around it was to create a string variable(oFile) in the LoadThePDF subroutine, to replace the value member.
    Private Sub LoadThePDF()
        With MyPDFSDK_ax1
            .OpenFile("", "")
            .ShowNavigationPanels(True)
            .ShowNavPanelByString("Pages")
        End With

        If (File.Exists(GVar.currentTempFile)) Then
            File.SetAttributes(GVar.currentTempFile, FileAttributes.Normal)
            File.Delete(GVar.currentTempFile)
        End If

        Dim oFile As String = GVar.SourceFolder + txtPartNum.SelectedText + ".pdf"
        Dim tFile As String = txtPartNum.SelectedText + ".pdf"
        GVar.currentTempFile = Path.GetTempPath + tFile
        If (File.Exists(oFile)) Then
            File.Copy(oFile, GVar.currentTempFile, True)
        Else
            GVar.currentTempFile = Nothing
            MessageBox.Show("ATTENTION " & GVar._UserName & ": You just FAT Fingered the part number try again", "ERROR: WRONG FILE NAME")
            txtPartNum.Focus()
            Exit Sub
        End If
        With MyPDFSDK_ax1
            .OpenFile(GVar.currentTempFile, "")
            .ShowNavigationPanels(True)
            .ShowNavPanelByString("Pages")
            .ZoomLevel = 1
            .ShowToolBar(True)
            .ShowTitleBar(False)
        End With

    End Sub

Open in new window


I also  have noticed that wildcard searches do not work which is the biggest con for our end users. I'm still looking into a way to implement the wildcard search down the road. this current configuration is good enough for most end users (can't make everyone happy all the time).

Thanks again Eric for all your help!
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41812394
0
 
LVL 1

Author Comment

by:Steve Williams
ID: 41812427
I think we are going to leave it as is the Autocomplete works great, the people who normally would use the autocomplete would rather have speed than function when looking up numbers. The search is super fast as it is now and I do not feel I should mess with a good thing. the majority of users will be very happy with the autocomplete textbox(I'm one of them). I did add the link to my bookmarks for later reference tho, never turn away good information.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

722 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