Reputation: 23
I have created a WinForms note app using C# and VS2015, in which the user can write notes and save it temporally while the form is opened. But once the user has closed the app and re-opened it, his saved notes will disappear. How can I save the notes for the next open so that he can see, edit and read them again? Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
table = new DataTable();
table.Columns.Add("Title", typeof(string));
table.Columns.Add("Message", typeof(string));
dataGridView1.DataSource = table;
dataGridView1.Columns["Message"].Visible = false;
dataGridView1.Columns["Title"].Width = 140;
}
private void btnNew_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
}
private void btnSave_Click(object sender, EventArgs e)
{
table.Rows.Add(textBox1.Text, textBox2.Text);
textBox1.Clear();
textBox2.Clear();
}
private void btnRead_Click(object sender, EventArgs e)
{
int index = dataGridView1.CurrentCell.RowIndex;
if (index > -1)
{
textBox1.Text = table.Rows[index].ItemArray[0].ToString();
textBox2.Text = table.Rows[index].ItemArray[1].ToString();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
int index = dataGridView1.CurrentCell.RowIndex;
table.Rows[index].Delete();
}
Upvotes: 1
Views: 320
Reputation: 836
The reason is that during execution of the program the image of the process is in the main memory (RAM) and when the program is finished, its pages are thrown out of the main memory and its data part is not going to save any where (its current data). When you run your program again the program became to process (comes from hard to main memory) and it loads from the first and does not have any knowledge about previous sessions unless your program itself refers to somewhere in hard disk and use the predefined data.
There are so many ways to do so, I say some of them:
1) Create and use a database which has the same criteria as your table here.
2) Make binary or text file using methods available in System.IO namespace which stores the content in file system (in your hard drive). When your project starts up, load the content from the stored file.
3) Use serialization which has different approaches in C#, for example use System.Xml.Serialization namespace.
Upvotes: 0
Reputation: 462
You can use your Application Settings to store some data. The default scope is "User" (stored by and for the current user only) but can also be "Application" (available for every user of your app).
You can access that data through Properties.Settings.Default.myCustomSetting;
Upvotes: 1