Sky7ure Sky7ure - 3 months ago 10
Vb.net Question

Alternative Process

I have 2 buttons and a DataGridView with 2 Columns (0 & 1).


  • The 1st button transfers a randomized cell from the Column(1) to a TextBox. Then, it stores that Cell in variable (a), plus the cell that opposites it in variable (b).

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim rnd As New Random
    Dim x As Integer = rnd.Next(0, Form1.DataGridView1.Rows.Count)
    Dim y As Integer = 1
    Dim a As String = Form1.DataGridView1.Rows(x).Cells(y).Value
    Dim b As String = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
    TextBox3.Text = a
    End Sub

  • The 2nd button, however, is supposed to compare if another TextBox's text has the same string variable (b) has as Strings. Now, if so, then it has to display a certain message and so on...

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    If TextBox4.Text = b Then '<<< ISSUE HERE!
    MsgBox("Correct! ^_^")
    ElseIf TextBox4.Text = "" Then
    MsgBox("You have to enter something first! O_o")
    Else
    MsgBox("Wrong! >,<")
    End If
    End Sub



The problem is that the variable (b) is surely not shared across the two "private" subs. And so, there is NOTHING to compare to in the 2nd button's sub! I presume that the solution here is to split the "randomization process" into a separate function, then execute it directly when the 1st button gets activated. Furthermore, that function's variables have to be SHARED somehow, and I certainly don't know how!

Answer

Turn the local variables into class fields.

Dim rnd As New Random
Dim x As Integer
Dim y As Integer
Dim a As String
Dim b As String

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    x = rnd.Next(0, Form1.DataGridView1.Rows.Count)
    y = 1
    a = Form1.DataGridView1.Rows(x).Cells(y).Value
    b = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
    TextBox3.Text = a
End Sub

These fields can now be accessed from every Sub, Function and Property.

See:
- VB.NET Class Examples
- Visual Basic .NET/Classes: Fields