Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am a VB.NET beginner. I had faced the issues on loading string array randomly and add into datagridview.

For the project, first of all, I will import the data from excel to datagridview. After that, I need to load the string array randomly and put it into the new column (ColumnC) added into datagridview. I have 4 string values, and I want the loop to be able to load 1 to 4 string values(minimum 1 to maximum 4) randomly into the column of datagridview.

For example:

Array = {"abc", "cde", "efg","hij"}

For the output, I want a random number of these 4 string values able to load into the columnC of datagridview, which mean that the output should be:

ColumnA || ColumnB || ColumnC ||
1 ||3 ||abc, cde ||
2 ||5 ||abc ||
3 ||7 ||abc, cde, efg,hij||
4 ||9 ||cde, efg ||


After loading the string loop randomly, I would like to add the random value into each row of ColumnC too. From the code, I am only able to load one random string value into 1 row of ColumnC only.

Can anyone provide some coding examples or solutions so that I can solve my issue? I had stuck with these issues for a few days, and hope that I can solve these issues as soon as possible.

Thank you very much.

What I have tried:

Dim rnd As New Random()
Dim ARR As String() = {"abc", "cde", "efg", "hij"}
For Each value In ARR.OrderBy(Function(x) Rnd.Next())
DataGridView1.Rows(1).Cells(1).Value = value
Next
Posted
Updated 20-Nov-20 3:10am

1 solution

VB
Dim rnd As New Random()
Dim ARR As String() = {"abc", "cde", "efg", "hij"}
For Each value In ARR.OrderBy(Function(x) Rnd.Next())
    DataGridView1.Rows(1).Cells(1).Value = value # this only writes in row 1
Next

Change the row value to an integer that increments each time round the loop.
VB
Dim rnd As New Random()
Dim ARR As String() = {"abc", "cde", "efg", "hij"}
Dim rownumber as Integer
For Each value In ARR.OrderBy(Function(x) Rnd.Next())
    DataGridView1.Rows(rownumber).Cells(1).Value = value
    rownumber++
Next
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900