繁体   English   中英

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

[英]How to Save Dynamically Added Control in C#

我有一个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++;

    }

在编程中保存对象称为“序列化”。 对于您的情况,您应该创建一个名为“ 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/zh-cn/nuget/quickstart/install-and-use-a-package-in-visual-studio

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM