如何在C#中保存动态添加的控件

时间:2019-02-21 07:55:41

标签: c# .net

我有一个Windows Form应用程序,只要用户单击“添加按钮”标签,它就会添加按钮。我希望这些按钮被永久保存,并且每当用户重新打开应用程序时,我也希望这些按钮也被加载。 这是我添加按钮的代码:

    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++;

    }

1 个答案:

答案 0 :(得分:1)

在编程中保存对象称为“序列化”。 对于您的情况,您应该创建一个名为“ SavedButton”或类似名称的新类,然后使用Json,XML或什至作为原始字节数据对其进行序列化,然后将其保存到文件中。我建议将Json与“ Newtonsoft.Json”包一起使用!

使用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;
    }
}

以下是有关如何在需要时在Visual Studio上安装Nuget软件包的教程:https://docs.microsoft.com/en-us/nuget/quickstart/install-and-use-a-package-in-visual-studio

顺便说一句,在该示例中,当我们保存一个按钮时,我们正在使用一个文件。因此,您应该使用SavedButton数组创建另一个类,以便可以将一个文件用于多个按钮!