简体   繁体   中英

How do I get a random item from a ListBox, then compare it in C#?

Currently, I have this:

Random random = new 
random.Next(1, strings.Items.Count);
strings.Select();
strings.SelectedItem = strings.Items[Convert.ToInt32(random)];
var str = strings.SelectedItem;
if (str == "stuff")
{
  //Here
}

It doens't give any errors in the output, but it won't run when I test it. I get an InvalidCastException , saying it was unable to cast an object of type System.Random to the type System.IConvertible .

What does this error mean, and how can I fix it?

Your original code shouldn't compile (You missed new Random(); on the first line). It should be:

Random random = new Random();
int randomNumber  = random.Next(1, strings.Items.Count);
strings.Select();
strings.SelectedItem = strings.Items[randomNumber];
var str = strings.SelectedItem;
if (str == "stuff")
{
    //Here
}

You are getting the exception on following line, which tries to convert random object to the int, that you can't do and that is why you are getting the exception.

strings.Items[Convert.ToInt32(random)]

It is wrong to index the string.Items based on the random object. It should be the random number returned by the random object, not the object itself.

Change the code to following:

Random random = new 
int rnd = random.Next(1, strings.Items.Count);
strings.Select();
strings.SelectedItem = strings.Items[rnd];
var str = strings.SelectedItem;
if (str == "stuff")
{
  //Here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM