简体   繁体   中英

Looping Through C# Textboxes

I'm trying to have the user input doubles into 4 different textBoxes. Then, once the user clicks the calculate button, the following will happen:

  • foreach loop runs, parses textbox.Texts to doubles, and then adds them to a list
  • for loop runs and indexes through the list, adding them all up.
  • List item sum from previous step is divided by the number of values in the list result is entered into another textbox.

When I run it, no errors happen, but the result is not displayed in the texbox. Why is nothing getting displayed?

private void CalculateButton_Click(object sender, EventArgs e)
        {
            double gpa = 0;
            List<double> grades = new List<double>();

            foreach(Control textBox in Controls)
            {
                if ((textBox.GetType().ToString() == "System.Windows.Form.Textbox") && (textBox.Name.Contains("gradeBox")))
                {
                    grades.Add(double.Parse(textBox.Text));
                }
            }

            for(int i =0; i<grades.Count; i++)
            {
                gpa += grades[i];
            }
            gpa /= grades.Count;

            gpaBox.Text = gpa.ToString();
        }

Looks like the namespace of textbox is not quite correct. It should be System.Windows.Form s .Text B ox. Notice "s" and capital "B". Following is the corrected version.

private void CalculateButton_Click(object sender, EventArgs e)
        {
            double gpa = 0;
            List<double> grades = new List<double>();

            foreach (Control textBox in Controls)
            {
                if ((textBox.GetType().ToString() == "System.Windows.Forms.TextBox") && (textBox.Name.Contains("gradeBox")))
                {
                    grades.Add(double.Parse(textBox.Text));
                }
            }

            for (int i = 0; i < grades.Count; i++)
            {
                gpa += grades[i];
            }
            gpa /= grades.Count;

            gpaBox.Text = gpa.ToString();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM