事先,对不起,如果这篇文章看起来很混乱,因为我对英语很糟糕。
如何使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
}
我还是一名初学者和自学成才的程序员。感谢。
答案 0 :(得分:0)
我知道,您的代码会将随机特征分配给您的data
这是您的随机数:
string data = randomtrait.ToString();
为了分配checkedListBox1的值,你的代码必须是这样的:
string data = checkedListBox1.SelectedItems[randomtrait].ToString();
答案 1 :(得分:0)
由于我正在显示当前的评论,因为你正在显示randomtrait,它是一个整数,因此你得到一个数字。
我假设你打算做的事情如下。你有checkListBox包含多个项目。由于他们能够检查多个项目,因此只需单击此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();
}