Reputation: 39
I have a Windows Form application that adds buttons whenever user clicks on the Add Button label. I want these buttons to be saved Permanently and whenever user re-opens the application , I want those buttons to be loaded as well. Here is my code for adding the buttons:
private void AddSlot()
{
Button btn = new Button();
btn.Name = "Slot" + slotNm;
slotNm++;
btn.Location = new System.Drawing.Point(80, 80);
btn.BackColor = System.Drawing.Color.White;
btn.Size = new System.Drawing.Size(25, 25);
editPanel.Controls.Add(btn);
Drag(btn);
buttonsAdded.Insert(nSlot, btn); // dynamic list of buttons
nSlot++;
}
Upvotes: 0
Views: 606
Reputation: 508
Saving objects in programming is called "Serialization". In your case, you should create a new class named "SavedButton" or something like that, then serialize it using Json, XML or even as raw byte data, then save it to a file. I would recommend using Json with the package "Newtonsoft.Json" !
Example class structure using Newtonsoft.Json:
[System.Serializable]
public class SavedButton {
public string BtnName;
public System.Drawing.Point BtnLocation;
public System.Drawing.Color BtnColor;
public System.Drawing.Size BtnSize;
public static void Save(SavedButton button, string filePath) {
using (StreamWriter file = File.CreateText(filePath)) {
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, button);
}
}
public static SavedButton Load(string filePath) {
SavedButton button = null;
using (StreamReader file = File.OpenText(filePath)) {
JsonSerializer serializer = new JsonSerializer();
button = (SavedButton)serializer.Deserialize(file, typeof(SavedButton));
}
return button;
}
}
Here's a tutorial about how to install Nuget packages on Visual Studio if you need it: https://learn.microsoft.com/en-us/nuget/quickstart/install-and-use-a-package-in-visual-studio
By the way, in that example when we're saving one button, we're using one file. So you should make another class with an SavedButton array so you can use one file for multiple buttons !
Upvotes: 1