简体   繁体   中英

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?

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 <> "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM