简体   繁体   English

如何从ListBox中获取随机项,然后在C#中进行比较?

[英]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 . 我得到一个InvalidCastException ,说它无法将System.Random类型的对象InvalidCastExceptionSystem.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). 您的原始代码不应该编译(您错过了new Random();在第一行)。 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. 您正在获取以下行的异常,该行尝试将random对象转换为int,您无法执行此操作,这就是您获得异常的原因。

strings.Items[Convert.ToInt32(random)]

It is wrong to index the string.Items based on the random object. 索引string.Items基于random对象的错误。 It should be the random number returned by the random object, not the object itself. 它应该是random对象返回的随机数,而不是对象本身。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取列表框中所选项目的编号(C#) - How do I get the number of the item selected in a listbox (C#) 如何单击一个按钮,该按钮将从ListBox中删除一个项目,而该列表中包含C#中ListBox的信息? - How do I click a button that will remove an item from a ListBox and the List that holds the information for the ListBox in C#? C# - 如何找到列表框项的数据库键? - C# - How do I find the database key of a Listbox item? 如何在c#winforms应用程序中获取列表框项目的“密钥”? - How do I get at the listbox item's “key” in c# winforms app? c#如何获取列表框中的选定项目是否已更改。 ? - c# how do i get check if a selected item in a listbox has changed. ? 如何在C#中比较两个列表框的项目名称? - How to compare item name of two listbox in C#? 我如何获取XML属性以显示在列表框中C# - How do i get an XML attribute to display in a listbox c# 如何让 ListBox 显示来自文本框的“ID”的所有信息(ASP.NET C#) - How do I get a ListBox to display all info for an "ID" from a Textbox (ASP.NET C#) 如何从选定的ListBox控件的listboxitem获取属性? C# - How do i get a property from a selected ListBox Control 's listboxitem ? C# 如何使用C#检索/比较HTML列表框中的项目 - How do I retrieve / compare items in an HTML Listbox using C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM