1

Using vb. I'm trying to use the text of a combobox as the value of my font size. Means, as a user, I can choose which font size I'd like to have by clicking it out of the dropdown menu.

Dropdown menu:

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged ComboBox1.Items.Add("6") ComboBox1.Items.Add("10") ComboBox1.Items.Add("12") End Sub

Now the chosen option should affect the font size. But therefore, I need to convert from string to size. Anyone any help?

Also I could imagine there's a more efficient way to give a user the opportunity to change the font size. Any tips and advise is welcome!

  • Hi, What is it that you ant to change the font size of? Is it all controls on a form (labels, buttons, text boxes etc)? All controls of a specific type (all text boxes)? A single input control (single text box)? – Fazer87 Dec 14 '17 at 15:08
  • Hi, I just wanted it to affect one specific txtbox, like in your answer, exactly how it should work! Thanks alot! – arvenyon Dec 15 '17 at 15:59
  • Glad to hear it :) – Fazer87 Dec 15 '17 at 17:24
2

Something like this should work for you:

    Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Your combo box should be built and populated when the form loads, not when the combo box is changed
        ComboBox1.Items.Add("6")
        ComboBox1.Items.Add("10")
        ComboBox1.Items.Add("12")

        ComboBox1.SelectedIndex = 0 'This Auto-Selects the first entry to prevent you having to handle "null"'s
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim tryParseResult As Boolean 'holds the True/False for whether conversion to a number worked
        Dim parsedNumber As Integer 'Holds the number after conversion

        tryParseResult = Int32.TryParse(ComboBox1.SelectedItem, parsedNumber) 'try converting to number - "parsedNumber" will contain the number on success - "tryParseResult" will contain a true/false for success

        'If tryPArseResult = False - conversion failed - tell the user and stop.
        If tryParseResult = False Then
            MessageBox.Show("Conversion of " & ComboBox1.SelectedItem & " To Number Failed") 'Tell the user it failed
            Exit Sub 'Stop processing
        End If

        'Set TextBox1's Font to the same font with a new size
        TextBox1.Font = New Font(TextBox1.Font.Name, parsedNumber)

    End Sub
End Class

This should do the following: enter image description here

If you want to do this ith multipler controls - you need to look at looping through controls in a form using OfType if you only want to work on certain controls

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.