Mysterious “Parameter is not Valid” error

Well, just has a really weird “Parameter is not valid” ArgumentException exception being throw when trying to create a new TextBox.

e.g. Dim box As New TextBox()

Nothing weird about that you might think! The error was coming from down below, somewhere in the Font.GetHeight method.

Turned out that I was trying to be helpful in another part of code by Disposing of my Font objects

e.g.

Sub MakeBold(ByVal textbox1 As TextBox)
  Dim f As New Font(textbox1.Font, FontStyle.Bold)
  textbox1.Font.Dispose()
  textbox1.Font = f
End Sub

Well, turns out thats not a good thing to do after all. I was only doing it because of the the Code Analysis warning, CA2000:DisposeObjectsBeforeLosingScope – which keeps telling me to dispose my Font objects!

I assume the reason is its trying to access the disposed font somewhere else down the line, maybe it caches fonts to help you out, I don’t know. Anyway, changing it to this fixes the problem:

Sub MakeBold(ByVal textbox1 As TextBox)
  textbox1.Font = New Font(textbox1.Font, FontStyle.Bold)
End Sub

If anyone knows how to properly dispose the old font (if indeed you do need to) then let me know.