Search code examples
vb6

VB6 How to return a string value from form2 to form 1


in my project there are two forms: first form i named it frmSettings , i will use text boxes to save values in INI file. second form i named it frmSelectFolder , i had included with DirListBox and 2 Command buttons

enter image description here

as shown in attached image above in Settings form i have 8 text boxes and 8 command buttons to browse for folder path that it will be selected from frmSelectFolder

how to use frmSelectFolder for all text boxes without duplicating this form per each command button to return DirlistBox Control value ?


Solution

  • Here is some sample code for secondary frmSelectFolder form

    Option Explicit
    
    Private m_bConfirm          As Boolean
    
    Public Function Init(sPath As String) As Boolean
        Dir1.Path = sPath
        Show vbModal
        If m_bConfirm Then
            sPath = Dir1.Path
            '--- success
            Init = True
        End If
        Unload Me
    End Function
    
    Private Sub cmdOk_Click()
        If LenB(Dir1.Path) = 0 Then
            MsgBox "Please select a path!", vbExclamation
            Exit Sub
        End If
        m_bConfirm = True
        Visible = False
    End Sub
    
    Private Sub cmdCancel_Click()
        Visible = False
    End Sub
    
    Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
        If UnloadMode <> vbFormCode Then
            Cancel = 1
            Visible = False
        End If
    End Sub
    

    Here is how to call Init method above from primary frmSettings

    Option Explicit
    
    Private Sub cmdStartupPath_Click()
        Dim sPath           As String
        Dim oFrmSelector    As New frmSelectFolder
        
        sPath = txtStartupPath.Text
        If oFrmSelector.Init(sPath) Then
            txtStartupPath.Text = sPath
            txtStartupPath.SetFocus
        End If
    End Sub
    
    Private Sub cmdDownloadPath_Click()
        Dim sPath           As String
        Dim oFrmSelector    As New frmSelectFolder
        
        sPath = txtDownloadPath.Text
        If oFrmSelector.Init(sPath) Then
            txtDownloadPath.Text = sPath
            txtDownloadPath.SetFocus
        End If
    End Sub
    

    Here is a link to a complete sample project for you to research: SelectFolder.zip