1

我是 vb 的新手,我有 3 个文本框,当用户单击表单中的特定按钮时,我想将其设置为随机值:
这是代码:

Private Sub cmdjouer_Click(Index As Integer)
  txt1 = Math.Randomize(9)
 txt2 = Math.Randomize(9)
 txt3 = Math.Randomize(9)
End Sub

我收到以下错误 expected function or variable

我确定问题与随机函数有关。

任何想法将不胜感激

4

3 回答 3

12

You are confusing VB.NET with VB6. They are drastically different from each other. In the future, when you look for examples, documentation, and help online, be sure to specify VB6 to ensure that you are dealing with the correct language. They are essentially two completely different languages.

VB6

In VB6, you need to initially seed the random number generator using the Randomize function. Then, to generate a random number, you must use the Rnd function, for instance:

Private Sub cmdjouer_Click(Index As Integer)
    Randomize()
    txt1.Text = Int((Rnd * 9) + 1)
    txt2.Text = Int((Rnd * 9) + 1)
    txt3.Text = Int((Rnd * 9) + 1)
End Sub

VB.NET

Math.Randomize is a method in the Smart Personal Objects Technology (SPOT) namespace. I doubt that is what you are actually looking for. You probably just want to use the System.Random class, like this:

Private Sub cmdjouer_Click(sender As Object, e As EventArgs) Handles cmdjouer.Click
    Dim r As New Random()
    txt1.Text = r.Next(9).ToString()
    txt2.Text = r.Next(9).ToString()
    txt3.Text = r.Next(9).ToString()
End Sub

As others have pointed out, you don't want to set your text box reference variable to the number (e.g. txt1 = ...). You need to set the Text property of the text box.

Also, as was pointed out in the comments below, I called Randomize or created the New Random object inside the button's Click event. I did so to simplify the example, but in actuality, that would be bad practice. In either case, the seeding of the random number generator should, ideally, only happen once, typically when the application starts. By re-seeding the generator each time, it can cause the results to be less random.

于 2013-02-19T17:21:38.913 回答
2
于 2013-02-19T17:19:34.740 回答
2

Try this

' Initialize the random-number generator.
Randomize()
' Generate random value between 1 and 6.
Dim value As Integer = CInt(Int((6 * Rnd()) + 1)) txt1.text = cstr(value)
于 2013-02-19T17:20:08.630 回答