Here, I did the code you would like to have.
There is maybe some work to be done in the cell vadidating (data validation; if email and tel.number are correct), and this is about it.
When you do some changes, you press one button, and all it saves automatically (or you update or delete).
Code:
public partial class Form1 : Form
{
private string filePath;
List<Addressar> list;
public Form1()
{
InitializeComponent();
filePath = @"C:\1\Addressar.txt";
list = new List<Addressar>();
}
protected override void OnShown(EventArgs e)
{
GetData();
dataGridView1.AllowUserToAddRows = true;
dataGridView1.DataSource = new BindingSource(list, null);
}
private void GetData()
{
if (System.IO.File.Exists(filePath))
{
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] columns = line.Split(new string[] { "-:-" }, StringSplitOptions.RemoveEmptyEntries);
Addressar adr = new Addressar();
adr.Id = int.Parse(columns[0]);
adr.First = columns[1];
adr.Last = columns[2];
adr.Email = columns[3];
adr.Phone = columns[4];
list.Add(adr);
}
}
if (list.Count == 0)
MessageBox.Show("File exists, but there is no data inside of it.");
}
else
MessageBox.Show("File to read data from it, does not yet exist.");
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (Addressar adr in list)
{
string[] columns = new string[5];
columns[0] = adr.Id.ToString();
columns[1] = adr.First;
columns[2] = adr.Last;
columns[3] = adr.Email;
columns[4] = adr.Phone;
sb.AppendLine(String.Join("-:-", columns));
}
if (sb.Length > 0)
{
System.IO.File.Delete(filePath);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (TextWriter tw = new StreamWriter(fs))
{
tw.Write(sb.ToString());
MessageBox.Show("Update has been done successfully.","Data updating"); …