我试图在一个消息框中列出所有组合框项目.但是我所得到的是每个项目都出现在自己的消息框中.我知道消息框需要在循环之外,但是当我这样做时,它说该变量未分配.任何帮助都会很棒.
私人无效displayYachtTypesToolStripMenuItem_Click(对象发送者,EventArgs e)
{
string yachtTypesString;
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString=typeComboBox.Items[indexInteger].ToString();
MessageBox.Show(yachtTypesString);
}
}
解决方法:
像这样做,
StringBuilder yachtTypesString = new StringBuilder();
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString.AppendLine(typeComboBox.Items[indexInteger].ToString());
}
MessageBox.Show(yachtTypesString.ToString());
注意:不要使用字符串进行字符串连接,请使用StringBuilder对象在字符串中创建新实例.