Type Conversion in Calculation in VB.NET

In this article I will describe about Conversion of input values.
  • 2719

Introduction  

Here I am going to explain why conversion  i.e. "Conversion from string "" to type 'Integer'  is necessary for calculation by using Microsoft Visual Basic Express 2010. Initially we take two TextBoxes in which we will enter the the integer value and take one Button, with clicking on button we are supposed to multiplication of Textbox values.

Example

m1.gif  

If we code in Button_Click event as following:
 
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim
a As Integer = TextBox1.Text
D
im b As Integer = TextBox2.Text
Dim
z As Integer = a * b
MsgBox(z)
End Sub

In this manner although logic is correct however it will generate error.

Solution

It generates error because we are trying to assign a string value to an integer variable.
In order to do the assignment we should first determine that the conversion is possible. If the conversion is possible we can use Convert to do the conversion.

code will be as follow
 

Public Class Form

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim a As Integer = Convert.ToInt32(TextBox1.Text)
Dim b As Integer = Convert.ToInt32(TextBox2.Text)
Dim z As Integer = a * b
MsgBox(z)
End Sub

When we execute above code and put the values on both TextBox

m2.gif

When we click on Button for calculation we will find result as:

m3.gif

Conclusion

Replace "ToInt32" with the appropriate conversion.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.