Bhavani Kannan
Bhavani Kannan

Reputation: 1279

VB2008 Type Cast Exception

I have a form that has a textbox (say TextBox1). This field is of string type.

On clicking on a button, I have the below code

Dim field1 As String

If (TextBox1.Text) Then field1 = TextBox1.Text Else MsgBox("TextBox1 Code can not be empty. Enter proper value!", vbCritical, "Empty TextBox1")

I built the solution and ran it. When the form is opened, I did not enter anything in TextBox1. I clicked on the button. It throws an exception as below:

InvalidCastException was unhandled
Conversion from string "" to type 'Boolean' is not valid.

Can anyone guide as to how can I handle this exception? Also, why is it trying to convert my string to a Bool anyway?

Upvotes: 0

Views: 134

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503469

The problem is this part:

If (TextBox1.Text)

It's trying to convert TextBox1.Text to Boolean to see whether or not to go into the block. You might have meant:

If (TextBox1.Text <> "")

Upvotes: 1

Related Questions