簡體   English   中英

如果c#中包含一些按鈕,如何保存動態創建的用戶控件?

[英]How can I save a dynamically created user control if it contains some buttons in c#?

我是C#的新手。 我正在使用Windows窗體,並且我擁有包含兩個按鈕的Form1(一個在運行時創建用戶控件,另一個在運行時創建用戶控件的按鈕)。

如果單擊add_UserControl按鈕,此代碼將創建用戶控件和FlowLayoutPanel (以組織按鈕位置)。 然后,如果您單擊Add_Buttons按鈕,它將在FlowLayoutPanel上創建按鈕,並且所有這些操作均在運行時完成。

現在在Form1我創建了用戶控件和FlowLayoutPanel ,然后創建了5個按鈕,如何在SQL數據庫中將其用戶控件的屬性/細節及其FlowLayoutPanel和5個按鈕保存到SQL數據庫中,以便以后可以使用它們? 我一直在想一個主意,但我上網了,但沒有運氣。

任何想法? 請幫我。 謝謝

 public partial class Form1 : Form
{
    FlowLayoutPanel FLP = new FlowLayoutPanel();
    UserControl uc = new UserControl();


 private void add_UserControl_Click(object sender, EventArgs e)
    {

        uc.Height = 700;
        uc.Width = 900;
        uc.BackColor = Color.Black;
        Controls.Add(uc); //add UserControl on Form1


        FLP.Height = 600;
        FLP.Width = 800;
        FLP.BackColor = Color.DimGray;
        uc.Controls.Add(FLP); // add FlowLayoutPanel to UserControl
    }


    private void Add_Buttons_Click(object sender, EventArgs e)
    {

        //####### add buttons to FlowLayoutPanel ############

        Button dynamicButton = new Button();
        dynamicButton.Height = 50; 
        dynamicButton.Width = 200;
        dynamicButton.BackColor = Color.Green;
        dynamicButton.ForeColor = Color.Blue;
        dynamicButton.Text = "";
        FLP.Controls.Add(dynamicButton);



    }




}

好的,首先,您需要創建一個類,該類將代表具有所需屬性的按鈕之一。

class MyButton
{
    public string ButtonText {get;set;}
}

每次單擊並創建一個按鈕時,實際上都會創建一個此類的對象並將其添加到集合或列表中。 然后,您將需要一些其他代碼來監視該集合,並且每當它收到一個新條目時,它將創建一個新按鈕並將其Button文本設置為text屬性。 當列表成員消失時,它將刪除按鈕。

如果需要記住更多屬性(顏色,大小,字體等),也可以將它們添加到類中。 如果還需要其他控件,則可以始終創建公共父控件。

簡單。

如果希望能夠重新加載它,則可以將MyButton類定義為可序列化並將其存儲在xml文件中,並在構建時重新加載它。

您應該注意WPF及其MVVM模式。 它非常類似於它。 也可以看看命令模式,這是有用的模式。

您可以在一個SQL表中記住FlowLayoutsPanels,在另一個表中可以保存屬於這些FlowLayoutPanels的按鈕。

在“表單加載”或“應用程序加載”上,可以檢查SQL db中是否已經存在FlowLayoutPanels和相應的按鈕,如果是,則創建它們,否則什么也不做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM