C# Windows 表单应用程序 - 列表练习

C# Windows Form Application - Practicing with Lists

我是 C# 的新手,我正在制作不同的 windows 表单应用程序来练习。我遇到的问题之一是列出并将字符串转换为 int。现在我的表单上有标签、文本框和按钮。我正在尝试让用户一次在文本框中输入 1 个数字。然后我使用按钮让他们 "add" 将该项目添加到列表中。然后我想获取用户输入的所有内容并添加它们。基本上我正在尝试创建一个可用于计算几个测试或测验的平均值的表格(我想假设用户将输入整数,所以我不想使用双精度)。

private void btnQuizCalculate_Click(object sender, EventArgs e)
 {

int average;
int quizScore;

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

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

我不确定这是否是正确的方法,但我想让他们输入一个数字,然后当他们按下 btnQuizCalculate 时,该数字被存储,然后文本框再次清除,以便他们输入另一个数字。该按钮将做 3 件事:存储数字,获取平均值,并让用户有机会输入更多数字(如果他们愿意)。我在最后一部分遇到了麻烦,如果他们愿意,可以让他们输入更多数字。此外,我不确定使用焦点是否是一个好主意,因为我也不确定将其包含在何处。

您可以通过以下方式进行。

表格设计:

当您单击“添加”按钮时,会发生以下情况:

  1. TextBox中输入的Value被转换为Int并添加到List _scores中。

  2. 已找到列表 _scores 的平均值。

  3. 列表_分数的总和已确定。

  4. 分数和平均标签与值一起显示。

注意:使用ListBox控件进行演示。

以下是代码: - 不言自明。

 public partial class Form1 : Form
    {
        List<int> _scores = new List<int>();
        int average = 0;
        int quizScore = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {


            try
            {
                int _score = int.TryParse(textBox1.Text, out int converted) ? converted: 0; // Correct Way Of Handling As Mentioned In Comments
                _scores.Add(_score);
                listBox1.Items.Add(_score);
                textBox1.Text = null;

                average = (int)_scores.Average();
                quizScore = _scores.Sum();

                label1.Text = $"Score: {quizScore}";
                label2.Text = $"Average: {average}";

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
            }
        }
    }

希望这对您有所帮助。快乐学习。

也可以直接用列表来做

下面的代码是代码示例,你可以看看

   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());
            }
        }
    }
}