C# TextBox显示数字,而不是CheckedListBox中的单词

C# TextBox显示数字,而不是CheckedListBox中的单词,c#,visual-studio,checkedlistbox,C#,Visual Studio,Checkedlistbox,在此之前,如果这篇文章看起来让人困惑,我很抱歉,因为我的英语很差 如何使CheckedListBox上随机选择的项目显示在TextBox上?这是我的代码: private void generateButton_Click(object sender, EventArgs e) { textBox1.Clear(); Random random = new Random(); int randomtrait = random.Next(1, checkedListBox1

在此之前,如果这篇文章看起来让人困惑,我很抱歉,因为我的英语很差

如何使
CheckedListBox
上随机选择的项目显示在
TextBox
上?这是我的代码:

private void generateButton_Click(object sender, EventArgs e) {
    textBox1.Clear();
    Random random = new Random();
    int randomtrait = random.Next(1, checkedListBox1.CheckedItems.Count);
    checkedListBox1.SelectedItem = checkedListBox1.Items[randomtrait];
    string data = randomtrait.ToString();
    textBox1.Text = data;  //but it shows a number rather than text
}

我还是一个初学者,自学成才的程序员。谢谢。

我明白了,您的代码将随机特征分配给了您的
数据,这是您的随机数:

string data = randomtrait.ToString();
要分配checkedListBox1的值,您的代码必须如下所示:

string data = checkedListBox1.SelectedItems[randomtrait].ToString();

正如当前注释中突出显示的,因为您显示的是randomtrait,所以它是一个整数,因此您可以得到一个数字

我想你打算做的事情如下。您已选中包含多个项的列表框。由于它们可以检查多个项目,因此在单击此generateButton时,您希望显示其中一个已检查的项目。如果这是你的意图,那么可能有一些逻辑缺陷:

private void generateButton_Click(object sender, EventArgs e) {
    textBox1.Clear();
    Random random = new Random();

    // https://msdn.microsoft.com/en-us/library/2dx6wyd4.aspx
    // random.Next is inclusive of lower bound and exclusive on upper bound
    // the way you are accessing array, it is 0 based - thus you may not be able to picked up your first checked item
    int randomtrait = random.Next(1, checkedListBox1.CheckedItems.Count);

    // this set the 'selectedItem' to be something else from the whole list (rather than the checked items only).
    // checkedListBox1.SelectedItem = checkedListBox1.Items[randomtrait]; 

    // randomtrait is an integer, so data here would be numbers. This explains why next line displaying a number rather than text 
    //string data = randomtrait.ToString();

    textBox1.Text = data; 
}
可能是您想要的:

private void generateButton_Click(object sender, EventArgs e) {
    textBox1.Clear();
    Random random = new Random();
    int randomtrait = random.Next(0, checkedListBox1.CheckedItems.Count);
    textBox1.Text = checkedListBox1.CheckedItems[randomtrait].ToString();
}

数据是
randomtrait
它是
int
您可以使用
string data=checkedListBox1.SelectedItem.ToString()
来修复它。您希望您的代码显示什么?如果我理解您想要的内容,请尝试用
textBox1.Text=checkedListBox1.SelectedItem.ToString()替换
非常感谢。顺便说一下,它给了我一个错误,
int randomtrait无法将带[]的索引应用于“object”的表达式类型
adds in item,而不是
checkedListBox1.SelectedItem[randomtrait].toString()至“checkedListBox1.SelectedItems[randomtrait].toString();”谢谢在我创建新线程之前,您已经解决了我面临的多个问题。不用担心…=)很高兴这有帮助。