我正在尝试在一个消息框中列出所有组合框项目。但我得到的是每个项目都出现在自己的消息框中。我知道消息框需要在循环之外但是当我这样做时它表示变量是未分配的。任何帮助都会很棒。
private void displayYachtTypesToolStripMenuItem_Click(object sender,EventArgs e) {
string yachtTypesString;
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString=typeComboBox.Items[indexInteger].ToString();
MessageBox.Show(yachtTypesString);
}
}
答案 0 :(得分:3)
这样做,
StringBuilder yachtTypesString = new StringBuilder();
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString.AppendLine(typeComboBox.Items[indexInteger].ToString());
}
MessageBox.Show(yachtTypesString.ToString());
注意:不要使用字符串进行字符串连接,使用StringBuilder对象,因为在字符串中创建新实例。
答案 1 :(得分:1)
您可以尝试使用 Linq :
MessageBox.Show(String.Join(Environment.NewLine, typeComboBox.Items.Cast<String>()));
让它为你完成所有工作
答案 2 :(得分:0)
试试这个
string yachtTypesString="";
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString=yachtTypesString + typeComboBox.Items[indexInteger].ToString();
}
MessageBox.Show(yachtTypesString);
答案 3 :(得分:0)
列出一个消息框中的所有组合框项目
请使用以下代码来获取Combobox所有文本
private void Form1_Load(object sender,EventArgs e) { DataTable dtcheck = new DataTable(); dtcheck.Columns.Add(&#34; ID&#34); dtcheck.Columns.Add(&#34;名称&#34); for(int i = 0; i&lt; = 15; i ++) { dtcheck.Rows.Add(i,&#34; A&#34; + i); }
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = dtcheck;
}
}
private void button1_Click(object sender, EventArgs e)
{
string MessageText = string.Empty;
foreach(object item in comboBox1.Items)
{
DataRowView row = item as DataRowView;
MessageText += row["Name"].ToString() + "\n";
}
MessageBox.Show(MessageText, "ListItems", MessageBoxButtons.OK,MessageBoxIcon.Information);
}