How to delete and update a JSON string and bind it to a button?

  • Thread starter Thread starter samiarja
  • Start date Start date
S

samiarja

Guest
I am creating an application in C# windows form. This application will allow the user to enter data and then click "ADD" button, then this data will go to a structured JSON file. Now the user might need to delete one of the entries they made, therefore I have added a "Delete" and "Save" button to allow to user to delete and update the JSON string when needed.

Below is an example of the JSON file



[
{
"Record": 1,
"IPaddress": "192.148.34.34",
"Machinename": "user",
"username": "root",
"password": "root",
"sourcefolder": ".../.../...",
"destfolder": ".../.../...",
"filextension": "db",
"removedownloaded": 0
},
{
"Record": 2,
"IPaddress": "255.255.255.255",
"Machinename": "datalog",
"username": "root",
"password": "root",
"sourcefolder": "././././",
"destfolder": "./././.",
"filextension": "json",
"removedownloaded": 0
}
]

This is how the JSON string is created

class Datalogger
{
public int Record
{
get;
set;
}
public string IPaddress
{
get;
set;
}
public string Machinename
{
get;
set;
}
public string username
{
get;
set;
}
public string password
{
get;
set;
}
public string sourcefolder
{
get;
set;
}
public string destfolder
{
get;
set;
}
public string filextension
{
get;
set;
}
public int removedownloaded
{
get;
set;
}


Below is how the JSON string is re-created everytime the user enter new data.

private void button4_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to Add", "ADD", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{

filePath = @"C:\Users\Sami\Desktop\Companies\Nautitech Mining Systems Pty Ltd\Code\JSON\app-db.json";
// Update json data string
//jsonData = JsonConvert.SerializeObject(DataloggerList);
//System.IO.File.WriteAllText(filePath, jsonData);
string text = File.ReadAllText(filePath);

var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);

//Create new Datalogger

Datalogger myself = new Datalogger

{

Record = ++count,
IPaddress = textBox2.Text,
Machinename = textBox8.Text,
username = textBox4.Text,
password = textBox3.Text,
sourcefolder = textBox7.Text,
destfolder = textBox6.Text,
filextension = textBox5.Text,

};

if (currentList != null && currentList.Any())
{
var lastRecordNumner = currentList.OrderBy(q => q.Record).Last().Record;
myself.Record = lastRecordNumner + 1;

}
else
{
currentList = new List<Datalogger>();
}

currentList.Add(myself);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(output);
File.WriteAllText(filePath, output);
}
else
{
this.Activate();
}


}


Any thoughts on how to bind delete and save button to the JSON file to delete the string or update it.

I appreciate any idea, and thanks in advance.

Continue reading...
 
Back
Top