簡體   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