Results 1 to 25 of 25

Thread: Randomizing and For Next Loop (Resolved)

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Randomizing and For Next Loop (Resolved)

    I wrote some code that picks a random customer from a list of customers I import from an Excel Spreadsheet into a datagridview. Right now I am dealing with one list so it is a pretty straight forward process. However my boss wants me to adjust it so that a random employee is picked from each store (Store number is one of the fields in the datagridview).

    Here is the meat of the code I have so far.
    VB Code:
    1. Dim intRandom As Integer = GetRandom(0, CInt(txtTopNumber.Text))
    2.  
    3.         dgvCustomer.CurrentCell = _
    4.             dgvCustomer.Rows(intRandom).Cells(1)
    5.  
    6.         dgvCustomer.Rows(intRandom).Selected = True
    7.  
    8.         txtRandomSelectCust.Text = (CStr(dgvCustomer.Item(0, _
    9.             dgvCustomer.CurrentRow.Index).Value))

    The txtTopnumber.text is a field that holds that value of the row count so I could get my upper number: txtTopNumber.Text = CStr(intRowCount). Now I need to figure multiple top numbers and select a random customer from each group of stores. I think I need a for next loop to accomplish this but I am not sure how to get started. Any help or advice will be appreciated. Here is a snap shot of the datagrid that holds the store number. (V_LASTSTOR)

    Last edited by FastEddie; Sep 6th, 2006 at 10:07 AM.

  2. #2

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    I am closer but I am still missing the important piece. Here is my code up to this point. Basicaly I have stopped trying to do the randomization after the records are pulled into the dgv and am now trying to accomplish it at the same time using just the dataset.
    VB Code:
    1. Dim myDataset As New DataSet()
    2.         Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    3.             "Data Source=" & strFileName & ";" & "Extended Properties=""Excel 8.0;"""
    4.         Dim myData As New OleDbDataAdapter("SELECT FullName, V_ADDRESS, " & _
    5.             "V_CITY, V_STATE, V_ZIP, [Last Visit], V_LASTSTOR From [Mailing List$] WHERE " & _
    6.             "(V_STATE = 'MI') AND (Len(V_ZIP) >= 5) AND " & _
    7.             "(V_ADDRESS <> '') AND (V_CITY <> '') AND " & _
    8.             "(FullName <> '')", strConn)
    9.  
    10.         myData.TableMappings.Add("Table", "ExcelTest")
    11.         myData.Fill(myDataset)
    12.         dgvCustomer.DataSource = myDataset.Tables(0).DefaultView
    13.  
    14.         With myDataset.Tables(0)
    15.             Dim Stores(.Rows.Count - 1) As String
    16.             For i As Integer = 0 To .Rows.Count - 1
    17.                 ' For each ' Store in dataset ??? do something
    18.  
    19.                 ' Send to the randomization sub here.
    20.                 ' and then right to a DB (XML?) and
    21.                 ' goto the next random customer from
    22.                 ' the next store number
    23.  
    24.                 'Next
    25.             Next
    26.         End With
    Last edited by FastEddie; Sep 5th, 2006 at 06:01 PM.

  3. #3
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    1. Dose your database have a primary key?
    2. Do you know how many stores are there?
    3. Can you show the dataset columns? That I can see what may be the solution.

  4. #4
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    I think if you want to get a random employ from each store then you need to solve the problem in a store level first.

    1. What I am thinking is to get all the employees of a store.
    2. Get the rows count and pick a random row (employee).
    3. Do it for each store.

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    There is no primary key because I am working with an Excel file as my original datasource. There are allways going to be 29 Stores but the number of customers per store will vary each time the report is run. I think you meant customer ID and not employee ID but yes it sounds like you have the right idea.

    The Dataset columns are:

    Column 0 = FullName
    Column 1 = V_ADDRESS
    Column 2 = V_CITY
    Column 3 = V_STATE
    Column 4 = V_ZIP
    Column 5 = [Last Visit]
    Column 6 = V_LASTSTOR

  6. #6
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    I put some code together see if it works.
    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         Dim myDataset As New DataSet()
    3.         Dim stores As String() = {CStr(1101), CStr(1010),...}
    4.         Dim rendomCustQueue As Queue
    5.         Dim myrows As DataRow()
    6.         Dim value As Integer
    7.         ' Initialize the random-number generator.
    8.         Randomize()
    9.         For Each storeNum As String In stores
    10.             myrows = myDataset.Tables(0).Select("V_LASTSTOR ='" & storeNum & "'")
    11.             ' Generate random value between 0 and myrows size.
    12.             value = CInt(Int((myrows.GetUpperBound(0) * Rnd()) + 0))
    13.             rendomCustQueue.Enqueue(myrows(value).Item("FullName").ToString)
    14.         Next
    15.     End Sub

  7. #7

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    I am getting this error: Explicit initialization is not permitted for arrays declared with explicit bounds.

    on this line Dim Stores(5) As String = {1101, 1115, 1116, 1121, 1126, 1129}

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Randomizing and For Next Loop

    I'd recommedn not using Randomize and Rnd. Use a Random object:
    VB Code:
    1. Dim employeePicker As New Random
    2.  
    3. For Each store In myStores
    4.     employeeIndex = employeePicker.Next(employeeCount)
    5. Next store
    This glosses over a lot of the detail but basically for each store you generate a random number. If your employees have some ID number that forms an unbroken sequence then you can genereate a random value for that number directly. It's unlikely that that's the case though, so you'd probably generate a random employee index, then get the employee at that index in the table.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    I made a mstake. instad of
    VB Code:
    1. Dim Stores(5) As String = {1101, 1115, 1116, 1121, 1126, 1129}
    use this
    VB Code:
    1. Dim Stores As String() = {CStr(1101), CStr(1115), CStr(1116), CStr(1121), CStr(1126), CStr(1129)}

  10. #10
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    Or you can use Random object as jmcilhinney pointed.
    VB Code:
    1. Dim myDataset As New DataSet()
    2.  
    3.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    4.         Dim Stores As String() = {CStr(1101), CStr(1115), CStr(1116), CStr(1121), CStr(1126), CStr(1129)}
    5.         Dim rendomCustQueue As New Queue
    6.         Dim employeePicker As New Random
    7.         Dim myrows As DataRow()
    8.         Dim value As Integer
    9.  
    10.         For Each storeNum As String In Stores
    11.             myrows = myDataset.Tables(0).Select("V_LASTSTOR ='" & storeNum & "'")
    12.             ' Generate random value between 0 and myrows size.
    13.             value = employeePicker.Next(0, myrows.GetUpperBound(0))
    14.             rendomCustQueue.Enqueue(myrows(value).Item("FullName").ToString)
    15.         Next
    16.     End Sub

  11. #11

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    Thanks VBDT we are getting closer. I am getting this error: Index was outside the bounds of the array.

    I tried to figure out where the bounds are coming from but couldn't.

  12. #12
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    on wich line?

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Randomizing and For Next Loop

    The maximum value you specify should be one more than the maximum value you actually want returned. That measn that this line:
    VB Code:
    1. value = employeePicker.Next(0, myrows.GetUpperBound(0))
    should actually be:
    VB Code:
    1. value = employeePicker.Next(0, myrows.GetUpperBound(0) + 1)
    or, more sensibly:
    VB Code:
    1. value = employeePicker.Next(0, myrows.Length)
    Given that zero is the default minimum that simplifies to:
    VB Code:
    1. value = employeePicker.Next(myrows.Length)
    much as I posted previously.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  14. #14
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    and if you are using the second one with Random object then change the line
    VB Code:
    1. value = employeePicker.Next(0, myrows.GetUpperBound(0))
    with this
    VB Code:
    1. value = employeePicker.Next(0, myrows.Length)

  15. #15
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    Ye a little too late but I figured that out. I have never used the random object so this is one more thing I added into my database (brain).

  16. #16

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    Here is the code I am using.
    VB Code:
    1. Dim Stores As String() = { _
    2.             CStr(1101), _
    3.             CStr(1115), _
    4.             CStr(1116), _
    5.             CStr(1121), _
    6.             CStr(1126), _
    7.             CStr(1129)}
    8.  
    9.         Dim rendomCustQueue As New Queue
    10.         Dim CustomerPicker As New Random
    11.         Dim myrows As DataRow()
    12.         Dim value As Integer
    13.  
    14.         For Each storeNum As String In Stores
    15.             myrows = myDataset.Tables(0).Select("LastStore ='" & storeNum & "'")
    16.             ' Generate random value between 0 and myrows size.
    17.             value = CustomerPicker.Next(0, myrows.Length)
    18.             rendomCustQueue.Enqueue(myrows(value).Item("FullName").ToString)
    19.         Next

    Index out of range on this line: rendomCustQueue.Enqueue(myrows(value).Item("FullName").ToString)

    I am going to change the "FullName" to the index number and see if that works. I 'll be back.

    Update: No that didn't make a difference.
    Last edited by FastEddie; Sep 5th, 2006 at 08:05 PM.

  17. #17
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    That would mean that "myrows" size is negative. Check this line to see if you are getting the rows from particular stores.
    VB Code:
    1. myrows = myDataset.Tables(0).Select("V_LASTSTOR ='" & storeNum & "'")

  18. #18
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    Quote Originally Posted by VBDT
    and if you are using the second one with Random object then change the line
    VB Code:
    1. value = employeePicker.Next(0, myrows.GetUpperBound(0))
    with this
    VB Code:
    1. value = employeePicker.Next(0, myrows.Length)
    I forgat to ask, did you make the changes abov?

  19. #19

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    Yea I did make the changes. When I set the store like this

    myrows = myDataset.Tables(0).Select("LastStore =1126")

    There are no errors so you are right it has something to do with the store numbers line.

    Now that I have had some more time to think about I think it it is because store numbers are numbers and not text. I should be able to adjust that in the code. Be right back.

    Same error with this myrows = myDataset.Tables(0).Select("LastStore = " & storeNum)
    Last edited by FastEddie; Sep 5th, 2006 at 08:23 PM.

  20. #20
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    well it has to be like this. you need to have the store number between two single quotes for string number! I would recomend to make the numbers as strings.
    VB Code:
    1. myrows = myDataset.Tables(0).Select("LastStore ='1126'")

  21. #21

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    myrows = myDataset.Tables(0).Select("LastStore = '1126'") worked. Although I don't know where the output is going.

  22. #22
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    the output is all the data rows from that store asigned to myrows.
    now sorry i have to go but i will try to answer your questions when i get home.

  23. #23

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    No need to apologize. I appreciate any and all the help you can and have provided.

    My question on the output is where can I verify that it is pulling a random customer from each store? I am not seeing any thing visual to confirm that it is doing so.

    By the way I am going to post the entire code block minus the Try Catch block just in case I am doing something wrong. It may stand out better this way.

    VB Code:
    1. Private Sub GetRandomCustomers()
    2.  
    3.         Dim myDataset As New DataSet()
    4.         Dim strConn As String = _
    5.             "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    6.             "Data Source=" & strFileName & ";" & _
    7.             "Extended Properties=""Excel 8.0;"""
    8.         Dim myData As New OleDbDataAdapter("SELECT " & _
    9.             "FullName, " & _
    10.             "V_ADDRESS as Address, " & _
    11.             "V_CITY as City, " & _
    12.             "V_STATE as State, " & _
    13.             "V_ZIP as Zip, " & _
    14.             "[Last Visit] as LastVisit, " & _
    15.             "V_LASTSTOR as LastStore " & _
    16.             "From [Mailing List$] WHERE " & _
    17.             "(V_STATE = 'MI') AND (Len(V_ZIP) >= 5) AND " & _
    18.             "(V_ADDRESS <> '') AND (V_CITY <> '') AND " & _
    19.             "(FullName <> '')", strConn)
    20.  
    21.         myData.TableMappings.Add("Table", "CustomerList")
    22.         myData.Fill(myDataset)
    23.         dgvCustomer.DataSource = myDataset.Tables(0).DefaultView
    24.  
    25.         Dim Stores As String() = { _
    26.             CStr(1101), _
    27.             CStr(1115), _
    28.             CStr(1116), _
    29.             CStr(1121), _
    30.             CStr(1126), _
    31.             CStr(1129)}
    32.  
    33.         Dim rendomCustQueue As New Queue
    34.         Dim CustomerPicker As New Random
    35.         Dim myrows As DataRow()
    36.         Dim value As Integer
    37.  
    38.         For Each storeNum As String In Stores
    39.  
    40.             myrows = myDataset.Tables(0).Select("LastStore = '1126'") '& storeNum & "'")
    41.             value = CustomerPicker.Next(0, myrows.Length)
    42.             rendomCustQueue.Enqueue(myrows(value).Item("FullName").ToString)
    43.         Next
    44.  
    45.         myData.Dispose()
    46.  
    47.     End Sub

  24. #24
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Randomizing and For Next Loop

    Let me explain to you what we are doing here.
    Since we can not get a random numbers from mixed dataset with rows from different stores, we should separate the rows of each store and then try to find a random number for each store. For example:
    Store 1126 has 30 rows in the dataset and the rest is from different stores. Now, we need to separate these 30 rows and find a random number from 0 to 30. The random number let say 19 is returned after calling the “CustomerPicker.Next” method is used to get the customer name from “myrows(19)” data array. Of course we need to use this process for all stores which we are doing it in the For Each loop. After the process is done you will have the random chosen customers in the Queue (rendomCustQueue). And this is about it. This is the code with coments
    VB Code:
    1. Private Sub GetRandomCustomers()
    2.  
    3.         Dim myDataset As New DataSet()
    4.         Dim strConn As String = _
    5.             "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    6.             "Data Source=" & strFileName & ";" & _
    7.             "Extended Properties=""Excel 8.0;"""
    8.         Dim myData As New OleDbDataAdapter("SELECT " & _
    9.             "FullName, " & _
    10.             "V_ADDRESS as Address, " & _
    11.             "V_CITY as City, " & _
    12.             "V_STATE as State, " & _
    13.             "V_ZIP as Zip, " & _
    14.             "[Last Visit] as LastVisit, " & _
    15.             "V_LASTSTOR as LastStore " & _
    16.             "From [Mailing List$] WHERE " & _
    17.             "(V_STATE = 'MI') AND (Len(V_ZIP) >= 5) AND " & _
    18.             "(V_ADDRESS <> '') AND (V_CITY <> '') AND " & _
    19.             "(FullName <> '')", strConn)
    20.  
    21.         myData.TableMappings.Add("Table", "CustomerList")
    22.         myData.Fill(myDataset)
    23.         dgvCustomer.DataSource = myDataset.Tables(0).DefaultView
    24.  
    25.         'Assign the store numbers to a string array
    26.         Dim Stores As String() = { _
    27.             CStr(1101), _
    28.             CStr(1115), _
    29.             CStr(1116), _
    30.             CStr(1121), _
    31.             CStr(1126), _
    32.             CStr(1129)}
    33.  
    34.         Dim rendomCustQueue As New Queue
    35.         Dim CustomerPicker As New Random
    36.         Dim myrows As DataRow()
    37.         Dim value As Integer
    38.  
    39.         'Loop through each store
    40.         For Each storeNum As String In Stores
    41.             'Get all the rows from specified store by "storeNum"
    42.             myrows = myDataset.Tables(0).Select("LastStore = '" & storeNum & "'")
    43.             'Checks to see if the store has any customer records.
    44.             'If not go to next store.
    45.             If myrows.Length > 0 Then
    46.                 'Use the rows count from the particular store to get a random number
    47.                 value = CustomerPicker.Next(0, myrows.Length)
    48.                 'Use the random number as an index in "myrows"
    49.                 'to get the customer name and push it in to Queue.
    50.                 rendomCustQueue.Enqueue(myrows(value).Item("FullName").ToString)
    51.             End If
    52.             'Go to the next store
    53.         Next
    54.         myData.Dispose()
    55.  
    56.         'The "rendomCustQueue has all the customers' names chosen randomly.
    57.  
    58.     End Sub
    I hope it is clear now!

  25. #25

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Randomizing and For Next Loop

    VBDT the error is gone and I think I understand what the code is doing. The part that is / was confusing me is the Queue. I have never worked with that before so I wasn't aware of how to take the data stored there and present it to the user.

    I Googled queue and found I can get to the data doing something like this (I hope I am doing it right).
    VB Code:
    1. For Each storeNum As String In Stores
    2.             myrows = myDataset.Tables(0).Select("LastStore = '" & storeNum & "'")
    3.             If myrows.Length > 0 Then
    4.                 value = CustomerPicker.Next(0, myrows.Length)
    5.  
    6.                 rendomCustQueue.Enqueue(myrows(value).Item("FullName").ToString)
    7.                 rendomCustQueue.Enqueue(myrows(value).Item("Address").ToString)
    8.                 rendomCustQueue.Enqueue(myrows(value).Item("City").ToString)
    9.                 rendomCustQueue.Enqueue(myrows(value).Item("State").ToString)
    10.                 rendomCustQueue.Enqueue(myrows(value).Item("Zip").ToString)
    11.                 rendomCustQueue.Enqueue(myrows(value).Item("LastStore").ToString)
    12.             End If
    13.             Dim en As System.Collections.IEnumerator = rendomCustQueue.GetEnumerator()
    14.             While en.MoveNext()
    15.                 txtRandomSelectCust.Text &= (en.Current.ToString & " ") & vbNewLine
    16.             End While
    17.         Next

    EDIT: I removed this part of the post because I think it should have its own thread, which I started here.

    Thanks again VBDT
    Last edited by FastEddie; Sep 6th, 2006 at 11:16 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width