0

Im trying to get the selected value of my 4 comboboxes and add them together automatically in a windows form. The comboboxes items are decimals, 0,75 , 0,8 etc. How do i add all the values selected from the comboboxes together into a textbox?

I have tried for 5 hours now and really cant figure it out. FYI im really a beginner.

Thanks!

2
  • Use the ComboBox.SelectedIndexChanged event. Commented Oct 12, 2016 at 17:35
  • Even better yet switch to NumericUpDown controls which will return the value already cast to a number Commented Oct 12, 2016 at 17:48

1 Answer 1

1

You can handle TextChanged event on all combo boxes, calculate the sum and assign the result to the text box.

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I had a problem though, i got 2 more comboboxes in my form that i DONT want to add to the calculation but they seem to go in there anyways! :)
You can exclude the additional two combo boxes via filtering the query using Where lambda expression. gist.github.com/ivayle/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.