Link to home
Start Free TrialLog in
Avatar of Steve Williams
Steve WilliamsFlag for United States of America

asked on

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

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

Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

if you place a breakpoint on row 42, does it stop?
Avatar of Steve Williams

ASKER

Eric, It does not stop when placing a breakpoint at code line 42!
This means that you have no file to show up in the combo.

is GVar.currentFilter empty?
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 ""
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

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.
ASKER CERTIFIED SOLUTION
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok thanks Eric, appreciate your help!
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

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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!
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!
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.