1

Is it possible to take data from sql table and pass into label(or variable) with random order and random number of data? something like this:

Sql data:

1 Nik
2 Steve
3 John
4 Denny
5 Joe
6 Mike
7 Elena
8 Michel

Output should be random on every button click:

Joe, Elena, Denny

Next click something like:

Nik, Mike, Steve, Joe, Elen

Btw data doesn't have to be from SQL. Is this possible to do in VB.NET?

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
LazaBre
  • 43
  • 7

3 Answers3

0

Load all names in Load event of form and store them in a member field, then you can use such function to get random count of names in a random order.

Public Function Shuffle(source As List(Of String)) As List(Of String)
    Dim rnd = New Random(Environment.TickCount)
    Return source.OrderBy(Function(item) rnd.Next()) _
                 .Take(rnd.Next(1, source.Count)).ToList()
End Function

And here is the usage:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim list = Shuffle(ListOfNames)
    MessageBox.Show(String.Join(", ", list))
    'Me.Label1.Text = String.Join(", ", list)
End Sub

Also to get data and store it in a member field:

'Store names here
Dim ListOfNames As List(Of String)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim connection = "Your Connection String"
    'Your Select Command, For example:
    Dim command = "SELECT Name From People"
    Dim table As New System.Data.DataTable
    Dim adapter As New System.Data.SqlClient.SqlDataAdapter(command, connection)
    adapter.Fill(table)

    'Store names for later use
    ListOfNames = table.Select().Select(Function(row) row.Field(Of String)(0)).ToList()
End Sub
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • good answer except of breaking one basic rule: [avoid using Load event handler for common operations](http://stackoverflow.com/questions/4933958/vs2010-does-not-show-unhandled-exception-message-in-a-winforms-application-on-a) – use constructor or Shown() handler instead – miroxlav Dec 20 '15 at 21:55
  • It doesn't work, i got error: Value of type 'List(of String)' cannot be converted to 'String()'... :P – LazaBre Dec 20 '15 at 23:34
  • Check your code, you probably defined `String()` instead of `List(of String)`. There is no `String()` in my code and I used `List(of String)` – Reza Aghaei Dec 20 '15 at 23:38
  • Here is screenshot :P http://i68.tinypic.com/117hjro.jpg 2 errors... Name and List.. :( – LazaBre Dec 20 '15 at 23:53
  • I made a mistake in renames. Last line of `Form1_Load`, should be : `ListOfNames = table.Select().Select(Function(row) row.Field(Of String)(0)).ToList()` - Edited the answer. – Reza Aghaei Dec 20 '15 at 23:57
  • @RezaAghaei Thank you very much for help, but it's 1am , and i work from 6am, so i will try code early in the morning ;) thank you very very much for helping me, And sorry for my stupid q, I'm n00b! – LazaBre Dec 21 '15 at 00:07
  • Hi, i still have problem with code, error in ""MessageBox.Show(String.Join(", ", List)) It says that error is in list... :( – LazaBre Dec 21 '15 at 12:38
  • Ok i did it :)) In line where is MsgBox .... Line, i just added list.ToArray :) and it's working, thank you very much bro – LazaBre Dec 21 '15 at 12:58
  • Good Job. But it should work even without it. never mind. It's important you made it work:) – Reza Aghaei Dec 21 '15 at 12:59
  • Just a small one - `rnd.Next(1, source.Count - 1)` should be `rnd.Next(1, source.Count)` as the upper bound is exclusive. – Enigmativity Dec 26 '15 at 12:05
  • Also using `Dim rnd = New Random(System.DateTime.Now.Millisecond)` is no better than `Dim rnd = New Random()`. They are both based on a millisecond count for the seed. – Enigmativity Dec 26 '15 at 12:08
  • @Enigmativity Thank you for the comment. I edited the answer to correct `Count-1`, and about the seed, I used `Environment.TickCount` to make it better. Hope you find the answer useful, But I doubt even if we need a seed? Do we need the seed? – Reza Aghaei Dec 26 '15 at 12:49
  • @RezaAghaei - `new Random()` already uses `Environment.TickCount` internally. So you don't need to specify the seed. – Enigmativity Dec 26 '15 at 22:37
0

If your querying the database each time, you can add an order by clause. Assuming MS SQL, something like

select * 
from people 
order by newid()
snoopy-do
  • 605
  • 4
  • 16
-1

I've created an example in which the data is in a List. This custom class Person is simply to capture you're original example above:

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
}

This method randomizes the order of names in a List<Person>:

public string GetRandomNames(List<Person> people)
{
    int numberOfPeople = people.Count;
    string nameLabel;

    string[] names = new string[numberOfPeople];
    Random r = new Random();

    for(int i = 0; i<numberOfPeople; i++)
    {
        int randomIndex = r.Next(0, people.Count);
        names[i] = people[randomIndex].Name;
        people.RemoveAt(randomIndex);
    }
    foreach(string name in randomNames)
    {
        nameLabel += name + ", ";
    }

    return nameLabel;
}

For the purposes of this Example, I've created the List as below. Of course, your list would come from some other source, such as a the SQL database you mentioned.

List<Person> people = new List<Person>();
people.Add(new Person() { ID = 1, Name = "Nik" });
people.Add(new Person() { ID = 2, Name = "Steve" });
people.Add(new Person() { ID = 3, Name = "John" });
people.Add(new Person() { ID = 4, Name = "Denny" });
people.Add(new Person() { ID = 5, Name = "Joe" });
people.Add(new Person() { ID = 6, Name = "Mike" });
people.Add(new Person() { ID = 7, Name = "Elena" });
people.Add(new Person() { ID = 8, Name = "Michel" });

Usage would then be something along the lines of:

string nameLabel = GetRandomNames(people);

Please let me know if this doesn't answer your question.

Scott
  • 27
  • 1
  • 7