fedeteka fedeteka - 2 months ago 9
Vb.net Question

Save user selection from a New Form

I will generate a PDF with 3 possible themes so I need to show the user a form with 3 radio buttons to pick one.

On my Form1

With the line

SelectedTheme = ChooseTheme()


I call this Function

Private Function ChooseTheme() As String
Dim formChooseTheme = New ChooseThemeForm()
formChooseTheme.Show()
Return ChooseTheme
End Function


The Form ChooseTheme() is the one with the 3 radio buttons and one cmd Button with this code:

Public Class ChooseTheme
Private Sub cmdChoose_Click(sender As Object, e As EventArgs) Handles cmdChoose.Click

If optNormal.Checked = True Then Theme = "Normal"
If optElegante.Checked = True Then Theme = "Elegant"
If optModerno.Checked = True Then Theme = "Modern"
Me.Close()
End Sub
End Class


But I can't make it work. I'm confused about where and how to define (DIM) the Theme or/and ChooseTheme variable. As a Public variable on the Form1 ?

Answer

In part, you might be confused because there is a form class and also a function named ChooseTheme. The function appears to be flawed:

Private Function ChooseTheme() As String
    Dim formChooseTheme = New ChooseThemeForm()
    formChooseTheme.Show()
    Return ChooseTheme
End Function

Is the form class name ChooseThemeForm or ChooseTheme as shown in your second code block? Either way, the function return value is never set.


If there are only three selections, I'd try to fit a ComboBox on the first form somewhere to prevent having to use a new form for such a small job. Another alternative would be a menu item that is checked.

To use a form, you should probably show the theme selector as a dialog - the user cannot proceed until something is picked. That way you can be sure you know when they have made a selection and it allows them to cancel/abort.

' local var to hold the theme
Private PDFTheme As String
...
' code to get selection

Using dlg As New frmThemeSelector
    If dlg.ShowDialog <> DialogResult.Cancel Then
        PDFTheme = dlg.SelectedTheme
    End If
End Using

Then in the ThemeSelector form, you expose a property which hold their selection:

Public Property SelectedTheme As String = "Default"

Since you indicated radio buttons, initialize the property to match the default button value. Note also that a Dialog doesn't not get automatically disposed when it is closed, you need to do that. The code above uses a Using block to dispose of it.

I would also suggest using a PDFStyle Enum for the variable rather than just a string.