random result displayed in a textbox from array

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

45 Replies - 8713 Views - Last Post: 30 July 2010 - 08:41 AM Rate Topic: -----

#1 Guest_Justin*


Reputation:

random result displayed in a textbox from array

Posted 14 July 2010 - 11:20 AM

Hello,

I'm new to VB and I'm learning off of Google, DIC and the rest of the internet.

I'm a police officer and trying to write a program which will print the officers name, start and end dates and select a random road from an array that he/she will be responsible for during the time period. Right now I only have 6 entered to try and get the hang of this. It has a drop down list of persons names, a start date picker and an end date picker. The program will then display the name, start and end date and select a random road from the array.

As of right now just messing around I cannot seem to get it to show up in a text box however I can get the start and end date and a result that pops up in a message box. (2 different boxes)

I cannot get the name from the drop down to display in the message box, it just shows up blank. Also the random choice from the array seems to display the first choice 2-3 times then displays the 2nd once or twice. So obviously something is incorrect on my code and expected since this is new to me. Here is what I have so far and be gentle I know its simple for you but its not for me at this time :)

Right now its set up to display in a message box because it was the only thing I could figure out so far.

Public Class Form1

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles officerComboBox1.SelectedIndexChanged

    End Sub

    Private Sub ProgressBar1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub DateTimePicker2(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub DateTimePicker1(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRUN.Click

        Dim road(5) As String

        'declare array of roadways

        road(0) = "Neptune Drive"
        road(1) = "Nautilus Drive"
        road(2) = "Mermaid Drive"
        road(3) = "Jennings Drive"
        road(4) = "Jonathan Drive"
        road(5) = "Parker Street"

        'Display a random result from the array

        MessageBox.Show("You are responsible for this roadway for the selected time period: " & road(Rnd))
        MessageBox.Show(startDate.Value & " - " & endDate.Value)

    End Sub

    Private Sub resultsTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


    End Sub

    Private Sub resetFormButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles resetFormButton1.Click
        officerComboBox1.Text = ""
        startDate.Value = Date.Today
        endDate.Value = Date.Today

    End Sub

    Private Sub endDate_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles endDate.ValueChanged

    End Sub
End Class



Is This A Good Question/Topic? 0

Replies To: random result displayed in a textbox from array

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,515
  • Joined: 23-August 08

Re: random result displayed in a textbox from array

Posted 14 July 2010 - 12:18 PM

Moved to VB.NET. VB6 is not the same as VB.NET...VB 6 is OLD.
Was This Post Helpful? 0
  • +
  • -

#3 Justin3085  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 20-December 09

Re: random result displayed in a textbox from array

Posted 17 July 2010 - 01:34 PM

ANyone? :(
Was This Post Helpful? 0
  • +
  • -

#4 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4485
  • View blog
  • Posts: 7,813
  • Joined: 08-June 10

Re: random result displayed in a textbox from array

Posted 17 July 2010 - 02:03 PM

Yes, don't use Rnd. It's old VB6, outdated.

Use the Random class. Also, I'd suggest using a List(of String) instead of an array.

Dim rand As New Random()
Dim roads As New List(Of String)
roads.Add("road 1")
roads.Add("road 2")
roads.Add("road 3")
roads.Add("road 4")
roads.Add("road 5")
roads.Add("road 6")
Console.WriteLine(roads.Count)
For i As Integer = 1 To 10
    Dim index As Integer = rand.Next(0, roads.Count)
    Console.WriteLine(roads(index))
Next
Console.ReadKey()


In my example, instead of using a message box, I'm writing it to the command prompt, but the principle is the same.

Also, another suggestion. Don't set your list in the Click event. That means every time you click the button, you're creating an array, and adding all the values to it. Make it a global variable and set it once, in the Form1_Load method.
Was This Post Helpful? 1
  • +
  • -

#5 Justin3085  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 20-December 09

Re: random result displayed in a textbox from array

Posted 17 July 2010 - 06:54 PM

View PostinsertAlias, on 17 July 2010 - 01:03 PM, said:

Yes, don't use Rnd. It's old VB6, outdated.

Use the Random class. Also, I'd suggest using a List(of String) instead of an array.

Dim rand As New Random()
Dim roads As New List(Of String)
roads.Add("road 1")
roads.Add("road 2")
roads.Add("road 3")
roads.Add("road 4")
roads.Add("road 5")
roads.Add("road 6")
Console.WriteLine(roads.Count)
For i As Integer = 1 To 10
    Dim index As Integer = rand.Next(0, roads.Count)
    Console.WriteLine(roads(index))
Next
Console.ReadKey()


In my example, instead of using a message box, I'm writing it to the command prompt, but the principle is the same.

Also, another suggestion. Don't set your list in the Click event. That means every time you click the button, you're creating an array, and adding all the values to it. Make it a global variable and set it once, in the Form1_Load method.


Thanks for the reply! Console would bee writing to the command prompt I'm guessing. I didn't really want to use the message box, it was just the only way I could see some action. Ideally I want it to show up in a text box but list Name, dates and road. I appreciate the reply... I feel like im a little further now and I can fiddle with the rest to get it to work. It may take me forever but, have to learn somehow! :)
Was This Post Helpful? 0
  • +
  • -

#6 rgfirefly24  Icon User is offline

  • D.I.C Lover
  • member icon


Reputation: 267
  • View blog
  • Posts: 1,476
  • Joined: 07-April 08

Re: random result displayed in a textbox from array

Posted 17 July 2010 - 07:07 PM

you would Set the textbox's Text property equal to your listitem.

I.E:

going off of InsertAlias' example:


Replace
Console.WriteLine(roads(index)) 


with
TextBox1.Text += roads(index)  


where TextBox1 is the name of your textbox you want to display the name in.

Now the thing you need to know here is that if you are wanting to Append text to the TextBox then use += or
TextBox1.Text = TextBox1.Text & roads(index)



Now if you want to just replace the text in the box with new text you would use just the =
TextBox1.Text = roads(index)


Was This Post Helpful? 1
  • +
  • -

#7 Justin3085  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 20-December 09

Re: random result displayed in a textbox from array

Posted 17 July 2010 - 09:31 PM

Thank you very much for the help. I placed the code in the Form1_load section however it only gave me the random roadway each time I ran the program. I placed it in the click event and it gave me the results I was looking for. I'm not sure if that is proper or not but it worked.

Its a small program but I've been plucking away at it each night and I learned a tremendous amount so far thanks to dream.in.code.

Now I just need to add a few more things and I have my very first program!

-Justin
Was This Post Helpful? 0
  • +
  • -

#8 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4485
  • View blog
  • Posts: 7,813
  • Joined: 08-June 10

Re: random result displayed in a textbox from array

Posted 17 July 2010 - 10:37 PM

You should make the list (roads) and the Random (rand) global. Outside the methods. Assign all the values to roads in the load event. Do the random selection portion in the click event.

Think about what is happening. In your code, each time you click, you are creating a new List, a new Random, and assigning all your road names to it, every time. Those parts should be done only once.
Was This Post Helpful? 1
  • +
  • -

#9 Justin3085  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 20-December 09

Re: random result displayed in a textbox from array

Posted 18 July 2010 - 07:46 AM

View PostinsertAlias, on 17 July 2010 - 09:37 PM, said:

You should make the list (roads) and the Random (rand) global. Outside the methods. Assign all the values to roads in the load event. Do the random selection portion in the click event.

Think about what is happening. In your code, each time you click, you are creating a new List, a new Random, and assigning all your road names to it, every time. Those parts should be done only once.


Perfect, I moved everything accordingly. Have to be honest though, it took me a few times reading your post before it clicked. I understand what you are saying about creating a new list each time the button is clicked. I also see why they are placed where they are as well. Things make more sense when someone is teaching you on the exact project your working on than my countless Google searches. I have an idea that as programs grow this would cause big issues. I plan on adding about 100 more roads to this so I would imagine I would have an issue if I left everything under the click event.

This is my pilot program so as I learn I'll be adding more things to it. :) Thank you again for the help!
Was This Post Helpful? 0
  • +
  • -

#10 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4485
  • View blog
  • Posts: 7,813
  • Joined: 08-June 10

Re: random result displayed in a textbox from array

Posted 18 July 2010 - 01:27 PM

Well, if you're going to be adding dozens or hundreds of rows, it won't be good to do it all in code. Then if you ever need to add more, you'll have to recompile. The best way to do that is to load the names from a file on your computer. And I just so happen to have modified my sample to show that, and a few other good practices:

Imports System.IO

Public Class Form1

    Private roads As New List(Of String)
    Private rand As New Random()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Do initial load
        LoadRoads()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'get a random road
        TextBox1.Text = GetRandomRoad()
    End Sub

    Private Sub LoadRoads()
        'where the file is
        Dim path = "c:\dev\roads.txt"
        'we want to use a stream reader
        Using sr As StreamReader = File.OpenText(path)
            'while there is still more in the text file
            While (Not sr.EndOfStream)
                'read a line
                Dim road = sr.ReadLine()
                'if the line isn't just empty space
                If Not road.Trim() = String.Empty Then
                    'add the line to the roads list
                    roads.Add(road)
                End If
            End While
        End Using
    End Sub

    Private Function GetRandomRoad() As String
        'get a random number
        Dim index = rand.Next(0, roads.Count)
        'return that road
        Return roads(index)
    End Function
End Class


I've added comments so it should be clear what's going on, but if it isn't feel free to ask questions. I enjoy helping those who actually want to learn.
Was This Post Helpful? 1
  • +
  • -

#11 Justin3085  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 20-December 09

Re: random result displayed in a textbox from array

Posted 23 July 2010 - 08:33 AM

View PostinsertAlias, on 18 July 2010 - 12:27 PM, said:

Well, if you're going to be adding dozens or hundreds of rows, it won't be good to do it all in code. Then if you ever need to add more, you'll have to recompile. The best way to do that is to load the names from a file on your computer. And I just so happen to have modified my sample to show that, and a few other good practices:

Imports System.IO

Public Class Form1

    Private roads As New List(Of String)
    Private rand As New Random()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Do initial load
        LoadRoads()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'get a random road
        TextBox1.Text = GetRandomRoad()
    End Sub

    Private Sub LoadRoads()
        'where the file is
        Dim path = "c:\dev\roads.txt"
        'we want to use a stream reader
        Using sr As StreamReader = File.OpenText(path)
            'while there is still more in the text file
            While (Not sr.EndOfStream)
                'read a line
                Dim road = sr.ReadLine()
                'if the line isn't just empty space
                If Not road.Trim() = String.Empty Then
                    'add the line to the roads list
                    roads.Add(road)
                End If
            End While
        End Using
    End Sub

    Private Function GetRandomRoad() As String
        'get a random number
        Dim index = rand.Next(0, roads.Count)
        'return that road
        Return roads(index)
    End Function
End Class


I've added comments so it should be clear what's going on, but if it isn't feel free to ask questions. I enjoy helping those who actually want to learn.

Ok, Ive re done everything but I cannot seem to get the random road choice to show up in the text box. Since its using this stream reader and the list is in a txt file on my hard drive I'm not sure how to get it to show up as I would imagine its different code...

Let me clarify it with the error I keep getting:
It points to 'Return roads(index) and says "Argument Out of range Exception"
parameter name 'index'

This post has been edited by Justin3085: 23 July 2010 - 08:44 AM

Was This Post Helpful? 0
  • +
  • -

#12 Justin3085  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 20-December 09

Re: random result displayed in a textbox from array

Posted 28 July 2010 - 05:36 AM

The error points to line 40 Return roads(index).
Would anyone point me in the right direction from here?
Was This Post Helpful? 0
  • +
  • -

#13 CharlieMay  Icon User is offline

  • This space intentionally left blank
  • member icon

Reputation: 1605
  • View blog
  • Posts: 5,162
  • Joined: 25-September 09

Re: random result displayed in a textbox from array

Posted 28 July 2010 - 06:16 AM

And at that point, what is the value of Index?


Rand.Next(0, roads.count) 0 being the minimum value, roads.count being the maximum value.

So if I have an array(8) I have 9 elements (0-8)
that means my array.count is 9

rand.next(0,array.count) means I can have a number from 0 to 9 but there is no element 9 so try:

rand.next(0,roads.count-1)


EDIT:
Well, apparently, I'm wrong with what I said above as I just tried your code verbatim and created a text file with a list of roads.

The code ran as I would have expected it to. With each click of the button, I got a random road listed in the textbox. I even dropped down to just two roads in my file and clicked the button at least 30 times and never got an error. Just random switching between the two roads.

Last Edit I promise ;)
In case anyone else can learn from this.
Didn't realize the maximum side of the rand.next was exclusive.

This post has been edited by CharlieMay: 28 July 2010 - 06:56 AM

Was This Post Helpful? 0
  • +
  • -

#14 Justin3085  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 20-December 09

Re: random result displayed in a textbox from array

Posted 28 July 2010 - 11:18 AM

I don't understand then why I'm getting the error. I run the program, but once I hit the button to generate the random road I get the error 'ArgumentOutOfRangeException'
Was This Post Helpful? 0
  • +
  • -

#15 CharlieMay  Icon User is offline

  • This space intentionally left blank
  • member icon

Reputation: 1605
  • View blog
  • Posts: 5,162
  • Joined: 25-September 09

Re: random result displayed in a textbox from array

Posted 28 July 2010 - 11:28 AM

what is the value of Index at that moment?

OK, I can re-produce the error by not having the file at the path specified. Check your path and make sure roads.txt actually resides there.
Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »