Search code examples
c#visual-studioprogramming-languageswindows-forms-designer

C# Windows Form Application - Practicing with Lists


I'm new to C# and I'm making different windows form applications to practice. One of the things that I'm having trouble with is lists and converting string to int. Right now I have a label, text box, and button on my form. I'm trying let the user enter 1 number at a time into the text box. Then I'm using the button to let them "add" that item to the list. Then I want to take all of those things that the user has entered and add them. Basically I'm trying to create a form that could be used to calculate the average of a couple of tests or quizzes (I want to assume the user will enter whole numbers so I don't want to use double).

private void btnQuizCalculate_Click(object sender, EventArgs e)
 {

int average;
int quizScore;

List<int> scores = new List<int>();

int quizTotal = Convert.ToString(txtQuizGrade.Text);
}

I'm not sure if this is the correct way to do this but I want to let them enter a number then when they push the btnQuizCalculate that number gets stored and then the textbox is clear again for them to enter another number. The button will do 3 things: store the numbers, get the average, and let the user have the chance to enter more numbers if they want. I'm having trouble with the last part, letting them enter more numbers if they want. Also I wasn't sure if using focus would be a good idea because I wasn't sure where to include that either.


Solution

  • You can also use the list directly to do it.

    The following code is a code example and you could have a look.

       public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            List<int> list = new List<int>();
            private void button1_Click(object sender, EventArgs e)
            {
                int a = 0;
    
                if (int.TryParse(textBox1.Text, out a) == false) 
                {
                    MessageBox.Show("Please input again");
                    textBox1.Clear();
                }
                else
                {
                    a = Convert.ToInt32(textBox1.Text);
                    list.Add(a);
                    label1.Text = string.Format("Average is {0}", list.Average());
                }
            }
        }
    }