Move the ‘Random rnd = new Random()’ line to class (form) level. This will solve one of issues.
In addition, make sure that the list box is not full, for example:
if( listBox1.Items.Count >= validStrings.Count)
{
// no more valid strings
return;
}
Check an alternative function too:
static readonly Random rnd = new Random( );
static readonly List<string> validStrings = new List<string>
{
"Banana",
"Avocado",
"Grape",
"Apple",
"Custard Apple",
"Cranberry"
};
private bool GenerateRandom( )
{
var unused_strings = validStrings.Except( listBox1.Items.Cast<string>( ) ).ToArray( );
if( unused_strings.Length == 0 ) return false;
string generated = unused_strings[rnd.Next( unused_strings.Length )];
listBox1.Items.Add( generated );
return true;
}