Reputation: 1
I'm trying to make a random band name generator in vb.net but whenever i randomly generate it shows a number rather than a word from my combo boxes
Public Class Form1
Private Sub btnMake_Click(sender As Object, e As EventArgs) Handles btnMake.Click
Randomize()
ComboBox1.Text = Int(Rnd() * ComboBox1.Items.Count)
ComboBox2.Text = Int(Rnd() * ComboBox2.Items.Count)
txtResult.Text = ComboBox1.Text + " " + ComboBox2.Text
End Sub
Private Sub btnFavourite_Click(sender As Object, e As EventArgs) Handles btnFavourite.Click
ListBox1.Items.Add(txtResult.Text)
End Sub
End Class
it should print one of the names that I've put into the combo box at random but it gives me random numbers instead
Upvotes: 0
Views: 237
Reputation: 15774
Put Option Strict On
at the top of your code file. You will see the compile error
Option Strict On disallows implicit conversions from 'Single' to 'String'.
on this line
ComboBox1.Text = Int(Rnd() * ComboBox1.Items.Count)
because Int() returns the integer portion of a number in the same type it was passed. So pass it a single, and it returns a single.
From Microsoft.VisualBasic metadata:
' Summary:
' Return the integer portion of a number.
' ...
Public Function Int(Number As Single) As Single
But you don't want to set the ComboBox.Text equal to a number anyway. You may want to set the ComboBox.SelectedIndex. You can try
ComboBox1.SelectedIndex = Int(Rnd() * ComboBox1.Items.Count)
but with Option Strict On
, you still have type mismatch because you're trying to set an integer to a single. You could wrap Int
in a CInt
conversion
ComboBox1.SelectedIndex = CInt(Int(Rnd() * ComboBox1.Items.Count))
but now it's getting out of hand...
Here's the issue: you're using outdated functions, Int
and Rnd
. These were brought over from VB6 days and if you use VB.NET functions, it's a whole lot easier. See the Random class. Using Random, you have access to Random.Next, which actually returns an integer. Great!
Dim r As New Random()
ComboBox1.SelectedIndex = r.Next(ComboBox1.Items.Count)
ComboBox2.SelectedIndex = r.Next(ComboBox2.Items.Count)
Here is the complete code (with an added event handler to update txtResult whenever the indices are changed i.e. when the user manually changes one)
Private Sub btnMake_Click(sender As Object, e As EventArgs) Handles btnMake.Click
Dim r As New Random()
ComboBox1.SelectedIndex = r.Next(ComboBox1.Items.Count)
ComboBox2.SelectedIndex = r.Next(ComboBox2.Items.Count)
End Sub
Private Sub ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged, ComboBox2.SelectedIndexChanged
txtResult.Text = ComboBox1.Text & " " & ComboBox2.Text
End Sub
Private Sub btnFavourite_Click(sender As Object, e As EventArgs) Handles btnFavourite.Click
ListBox1.Items.Add(txtResult.Text)
End Sub
Upvotes: 1
Reputation: 23
Set the SelectedIndex property instead of Text
ComboBox1.SelectedIndex = Int(Rnd() * ComboBox1.Items.Count)
Upvotes: 1