Skip to content

SAC Module 2 PRACTICE

Practice SAC 2

Click to view code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace StudentResultsApp
{
    public partial class Form1 : Form
    {
        private class StudentResult
        {
            public string StudentName { get; set; }
            public int Score { get; set; }

            public StudentResult() { }

            public StudentResult(string name, int score)
            {
                StudentName = name;
                Score = score;
            }
        }

        private BindingList<StudentResult> _results = new BindingList<StudentResult>();

        private readonly string _filePath =
            Path.Combine(Application.StartupPath, "results.csv");

        public Form1()
        {
            InitializeComponent();

            dgvResults.AutoGenerateColumns = true;
            dgvResults.ReadOnly = true;
            dgvResults.AllowUserToAddRows = false;
            dgvResults.AllowUserToDeleteRows = false;
            dgvResults.DataSource = _results;

            if (lblStatus != null)
            {
                lblStatus.Text = "Ready. Click Load/Show.";
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            List<StudentResult> loaded = LoadFromCsv(_filePath);

            _results.Clear();
            foreach (var r in loaded)
            {
                _results.Add(r);
            }

            if (lblStatus != null)
            {
                lblStatus.Text = $"Loaded {_results.Count} record(s).";
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string name = Prompt("Enter student name:");
            if (name == null) return;

            name = name.Trim();
            if (string.IsNullOrWhiteSpace(name))
            {
                MessageBox.Show("Name cannot be empty.");
                return;
            }

            string scoreText = Prompt("Enter score (0-100):");
            if (scoreText == null) return;

            if (!int.TryParse(scoreText.Trim(), out int score) || score < 0 || score > 100)
            {
                MessageBox.Show("Score must be an integer from 0 to 100.");
                return;
            }

            _results.Add(new StudentResult(name, score));

            if (lblStatus != null)
            {
                lblStatus.Text = "Added 1 record (not saved yet).";
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveToCsv(_filePath, _results.ToList());

            if (lblStatus != null)
            {
                lblStatus.Text = "Saved to results.csv";
            }
        }

        private List<StudentResult> LoadFromCsv(string filePath)
        {
            var results = new List<StudentResult>();

            if (!File.Exists(filePath))
                return results;

            string[] lines = File.ReadAllLines(filePath);

            foreach (string rawLine in lines)
            {
                string line = rawLine.Trim();
                if (string.IsNullOrWhiteSpace(line)) continue;

                if (line.Equals("StudentName,Score", StringComparison.OrdinalIgnoreCase))
                    continue;

                string[] parts = line.Split(',');
                if (parts.Length != 2) continue;

                string name = parts[0].Trim();
                if (int.TryParse(parts[1].Trim(), out int score))
                {
                    results.Add(new StudentResult(name, score));
                }
            }

            return results;
        }

        private void SaveToCsv(string filePath, List<StudentResult> results)
        {
            using (StreamWriter writer = new StreamWriter(filePath, false))
            {
                writer.WriteLine("StudentName,Score");

                foreach (var r in results)
                {
                    string safeName = (r.StudentName ?? "").Replace(",", " ");
                    writer.WriteLine($"{safeName},{r.Score}");
                }
            }
        }

        private string Prompt(string message)
        {
            // Project > Add Reference > Assemblies > Microsoft.VisualBasic
            return Microsoft.VisualBasic.Interaction.InputBox(message, "Input", "");
        }
    }
}