Generare dei numeri casuali è molto semplice grazie all'utilizzo della Classe Random, è invece un po' più macchinoso generare delle stringhe:
' VB.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To 99
Me.DataGridView1.Rows.Add(1)
' Aggiunge stringhe casuali.
Me.DataGridView1.Rows(i).Cells(0).Value = RandomString(i, CInt(Me.TextBox1.Text), CInt(Me.TextBox2.Text))
Next
End Sub
Private Function RandomString(ByVal randomSeed As Integer, ByVal maxChar As Integer, _Optional ByVal minChar As Integer = 1) As String
' Verifica i parametri.
If minChar < 0 Then
minChar = 0
End If
If maxChar < minChar Then
maxChar = minChar + 1
End If
Dim sb As New System.Text.StringBuilder
Dim pattern As String = "abcdefghijklmnopqrstuvxyz"
' Genera un numero casuale per impostare la lunghezza della stringa.
Dim rndLenght As New Random(randomSeed)
' Genera un numero casuale per identificare la posizione del carattere all'interno del pattern.
Dim rndIndex As New Random(randomSeed)
' Genera la stringa.
For i As Integer = 1 To rndLenght.Next(minChar, maxChar)
sb.Append(pattern.Substring(rndIndex.Next(0, pattern.Length - 1), 1))
Next
' Restituisce la stringa con la prima lettera maiuscola.
Return sb.Replace(sb(0), sb(0).ToString.ToUpper, 0, 1).ToString()
End Function// C#.
private void // Button1_Click(object sender, System.EventArgs e)
{
for (int i = 0; i <= 99; i++) {
this.DataGridView1.Rows.Add(1);
// Aggiunge stringhe casuali.
this.DataGridView1.Rows(i).Cells(0).Value = RandomString(i, (int)this.TextBox1.Text, (int)this.TextBox2.Text);
}
}
private string RandomString(int randomSeed, int maxChar, [System.Runtime.InteropServices.OptionalAttribute, _System.Runtime.InteropServices.DefaultParameterValueAttribute(1)] int minChar)
{
// Verifica i parametri.
if (minChar < 0) {
minChar = 0;
}
if (maxChar < minChar) {
maxChar = minChar + 1;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
string pattern = "abcdefghijklmnopqrstuvxyz";
// Genera un numero casuale per impostare la lunghezza della stringa.
Random rndLenght = new Random(randomSeed);
// Genera un numero casuale per identificare la posizione del carattere all'interno del pattern.
Random rndIndex = new Random(randomSeed);
// Genera la stringa.
for (int i = 1; i <= rndLenght.Next(minChar, maxChar); i++) {
sb.Append(pattern.Substring(rndIndex.Next(0, pattern.Length - 1), 1));
}
// Restituisce la stringa con la prima lettera maiuscola.
return sb.Replace(sb(0), sb(0).ToString.ToUpper, 0, 1).ToString();
}