Solved

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

Posted on 2016-09-22
14
27 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
  • 8
  • 6
14 Comments
 
LVL 69

Expert Comment

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

Author Comment

by:Steve Williams
Comment Utility
Eric, It does not stop when placing a breakpoint at code line 42!
0
 
LVL 69

Expert Comment

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

is GVar.currentFilter empty?
0
 
LVL 1

Author Comment

by:Steve Williams
Comment Utility
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 69

Expert Comment

by:Éric Moreau
Comment Utility
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
Comment Utility
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 69

Accepted Solution

by:
Éric Moreau earned 500 total points
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 1

Author Comment

by:Steve Williams
Comment Utility
Ok thanks Eric, appreciate your help!
0
 
LVL 1

Author Comment

by:Steve Williams
Comment Utility
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 69

Assisted Solution

by:Éric Moreau
Éric Moreau earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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 69

Expert Comment

by:Éric Moreau
Comment Utility
0
 
LVL 1

Author Comment

by:Steve Williams
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Wpf develop 5 29
Tabcontrol Caption? 1 21
Converting C# Objects into JSON file 7 36
How can I use this extension method? 8 35
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

771 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

12 Experts available now in Live!

Get 1:1 Help Now