2016-10-12 42 views
0

我试图获取我的4个组合框的选定值并将它们自动添加到窗体中。 组合框项目是小数,0,75,0,8等 如何将从组合框中选择的所有值一起添加到文本框中?在组合框中选择小数时自动计算值

我已经尝试了5个小时,现在真的不知道。 仅供参考,我真的是一个初学者。

谢谢!

+0

使用ComboBox.SelectedIndexChanged事件。 –

+0

更好的是,切换到NumericUpDown控件,它将已返回的值转换为数字 – tinstaafl

回答

1

您可以在所有组合框上处理TextChanged事件,计算总和并将结果分配给文本框。

private void Form1_Load(object sender, EventArgs e) 
{ 
    foreach (var comboBox in this.Controls.OfType<ComboBox>()) 
    { 
     comboBox.TextChanged += ComboBox_TextChanged; 
     InitializeComboBox(comboBox); 
    } 
} 

private void ComboBox_TextChanged(object sender, EventArgs e) 
{ 
    double result = 0; 
    foreach (var comboBox in this.Controls.OfType<ComboBox>()) 
    { 
     if (!string.IsNullOrEmpty(comboBox.Text)) 
     { 
      result += Convert.ToDouble(comboBox.Text); 
     } 
    } 

    textBox1.Text = result.ToString(); 
} 

private void InitializeComboBox(ComboBox comboBox) 
{ 
    for (int index = 0; index < 10; index++) 
    { 
     comboBox.Items.Add(index + 0.5); 
    } 
} 
+0

非常感谢! –

+0

虽然我遇到了一个问题,但我的表单中还有2个组合框,我不想添加到计算中,但它们似乎无论如何都放在那里! :) –

+0

您可以通过使用Where lambda表达式过滤查询来排除附加的两个组合框。 https://gist.github.com/ivayle/7209e5cca4d4856f847d6db9a8fb55a1#file-gistfile1-txt –