Reputation: 395
How to Recognize Variable Globally in VB.NET? I have the code below, my problem is that VB.NET does not recognize the variables "Z_lenght" and "Z_width" outside the IF Statement (i.e. after ENDIF).
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text > TextBox2.Text Then
Dim Z_lenght = TextBox1.Text
Dim Z_width = TextBox2.Text
Else
Dim Z_lenght = TextBox2.Text
Dim Z_width = TextBox1.Text
End If
Dim Z_area = Z_lenght * Z_width
RichTextBox1.AppendText("Length = " & Z_lenght)
RichTextBox1.AppendText("Width = " & Z_width)
RichTextBox1.AppendText("Area = " & Z_area)
End Sub
End Class
I appreciate any help/comment.
Upvotes: 0
Views: 130
Reputation: 1613
Public Class Form1
Dim Z_length As Double = 0
Dim Z_width As Double = 0
Dim Z_area As Double = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text > TextBox2.Text Then
' I don't know what you're trying to achieve here,
' but I recommend try using Double.TryParse()
Double.TryParse(TextBox1.Text, Z_length)
Double.TryParse(TextBox2.Text, Z_width)
Else
Double.TryParse(TextBox2.Text, Z_length)
Double.TryParse(TextBox1.Text, Z_width)
End If
Z_area = Z_length * Z_width
RichTextBox1.AppendText("Length = " & Z_length)
RichTextBox1.AppendText("Width = " & Z_width)
RichTextBox1.AppendText("Area = " & Z_area)
End Sub
End Class
This will make Z_Length
, Z_width
and Z_area
usable in class Form1
Upvotes: 2
Reputation: 636
declare your variables outside of the if else scope.
http://msdn.microsoft.com/en-us/library/1t0wsc67.aspx
If you declare a variable within a block, you can use it only within that block. In the following example, the scope of the integer variable cube is the block between If and End If, and you can no longer refer to cube when execution passes out of the block.
Given your comments, it seems you should review variable scopes. You can use your variables outside your if-else inside your if-else.
Upvotes: 0