解决方案
20
int Sum=0;
for(int i=0;i<panel1.Controls.Count;i++)
{
if( panel1.Controls[i] is ComboBox)
Sum+=int.Parse(panel1.Controls[i].Text);//这里未作数字合法性检查
}
20
private void button1_Click(object sender, EventArgs e) { int count = Convert.ToInt32(comboBox1.SelectedItem) + Convert.ToInt32(comboBox2.SelectedItem) +Convert.ToInt32(comboBox3.SelectedItem)+Convert.ToInt32(comboBox4.SelectedItem) +Convert.ToInt32(comboBox5.SelectedItem); }本人想放在循环里做,原因是后面可能还有更多的combobox怎么做?
int count; private void button1_Click(object sender, EventArgs e) { count = 0; foreach (Control ctrl in panel1.Controls) { if (ctrl is ComboBox) { ComboBox cmb = ctrl as ComboBox; count = Convert.ToInt32(cmb.SelectedItem) + count; } } MessageBox.Show(count.ToString()); }