c# wpf combobox average

后端 未结 1 546
别那么骄傲
别那么骄傲 2021-01-29 13:23

I want a simple code for my project , when i click in button average in textbox should appear the average of selected numbers in all combobox



        
相关标签:
1条回答
  • 2021-01-29 14:10

    You can use a foreach loop to traverse through each combobox to get the sum of all the items inside those comboboxes, keep it saved in a variable along with the count of all items in those comboboxes.

    Something like

    int intCBAverage;
    int intCBSum = 0;
    int intCBCount = 0;
    foreach (var item in cbnota6.Items) 
    {
        intCBSum += int.Parse(item.ToString());
        intCBCount++;
    }
    
    foreach (var item in cbnota7.Items) 
    {
        intCBSum += int.Parse(item.ToString());
        intCBCount++;
    }
    
    foreach (var item in cbnota8.Items) 
    {
        intCBSum += int.Parse(item.ToString());
        intCBCount++;
    }
    
    intCBAverage = intCBSum / intCBCount;
    

    The above piece of code is just for illustration of the idea. Hope you got the idea.

    Once you have the average, you can show that in the textbook.

    Also, instead of looping through each combobox you can loop through each control in the form, check whether the control is a combobox or not and if yes, then loop through the combobox items. Something like

    foreach (Control x in this.Controls)
    {
      if (x is ComboBox)
      {
        foreach (var item in x.Items)
        {
            intCBSum += int.Parse(item.ToString());
            intCBCount++;
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题