M7EX3

 avatar
unknown
csharp
2 years ago
2.4 kB
19
Indexable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace M7EX3
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// The default data file path
        /// </summary>
        private const string DataPath = "./data.txt";

        /// <summary>
        /// Initializes the form, creates the data file if it doesn't exist and
        /// updates the grid.
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            if (!File.Exists(DataPath)) File.Create(DataPath).Close();
            this.buttonList_Click(null, null);
        }

        /// <summary>
        /// Writes the given lines into the default data file.
        /// </summary>
        /// <param name="lines">Varargs for the specified lines.</param>
        private void DumpData(List<string> lines) => File.WriteAllLines(DataPath, lines.ToArray());

        /// <summary>
        /// Reads all the lines inside the default data file and returns them in the form of a list.
        /// </summary>
        /// <returns>A list containing all the default data file lines.</returns>
        private List<string> ReadData() => File.ReadAllLines(DataPath).ToList();

        /// <summary>
        /// Reads the information inside the textboxes and adds it into the existent information in a csv-like style.
        /// </summary>
        /// <param name="sender">The event sender</param>
        /// <param name="e">The event arguments</param>
        private void buttonInsert_Click(object sender, EventArgs e)
        {
            List<string> data = this.ReadData();
            data.Add($"{textName.Text},{numericAge.Value},{textJob.Text}");
            this.DumpData(data);
            
            textJob.Clear(); textName.Clear(); numericAge.Text = @"0";
        }

        /// <summary>
        /// Updates the DataGridView with the new information
        /// </summary>
        /// <param name="sender">The event sender</param>
        /// <param name="e">The event arguments</param>
        // ReSharper disable CoVariantArrayConversion
        private void buttonList_Click(object sender, EventArgs e)
        {
            List<string> data = this.ReadData();
            gridInfo.Rows.Clear();
            data.ForEach(x => gridInfo.Rows.Add(x.Split(',')));
        }
    }
}
Editor is loading...