首页 > 解决方案 > 保存动态创建的表单

问题描述

各位专家早安

我正在尝试将动态表单保存到文件中,表单没有与保存相关的属性。

如果我使用以下代码:

// Create a new instance of the form.
            Form form1 = new Form();
            // Create two buttons to use as the accept and cancel buttons.
            Button button1 = new Button();
            Button button2 = new Button();

            // Set the text of button1 to "OK".
            button1.Text = "OK";
            // Set the position of the button on the form.
            button1.Location = new Point(10, 10);
            // Set the text of button2 to "Cancel".
            button2.Text = "Cancel";
            // Set the position of the button based on the location of button1.
            button2.Location
               = new Point(button1.Left, button1.Height + button1.Top + 10);
            // Set the caption bar text of the form.   
            form1.Text = "My Dialog Box";
            // Display a help button on the form.
            form1.HelpButton = true;

            // Define the border style of the form to a dialog box.
            form1.FormBorderStyle = FormBorderStyle.FixedDialog;
            // Set the MaximizeBox to false to remove the maximize box.
            form1.MaximizeBox = false;
            // Set the MinimizeBox to false to remove the minimize box.
            form1.MinimizeBox = false;
            // Set the accept button of the form to button1.
            form1.AcceptButton = button1;
            // Set the cancel button of the form to button2.
            form1.CancelButton = button2;
            // Set the start position of the form to the center of the screen.
            form1.StartPosition = FormStartPosition.CenterScreen;

            // Add button1 to the form.
            form1.Controls.Add(button1);
            // Add button2 to the form.
            form1.Controls.Add(button2);

如何将其保存到 form1.cs 和 form1.designer.cs?我想保存这些文件,以便可以在其他项目中使用它们。

标签: c#winformsdynamic

解决方案


使用已经提供的应用程序设置:

Properties.Settings.Default.FormText = "Some Value"; //this is a string value, for checkboxes it can be boolean , ...
Properties.Settings.Default.Save(); 

你可以在这里找到更多关于它的信息

您可能还想以某种自定义格式将设置保存到文本文件中,或者只是序列化的 json 格式,但我推荐第一个选项。

编辑:

考虑到您的评论,表格被编译成 .exe 文件然后可以使用,保存.cs为文本格式的文件,您将无法使用它,但是,您可以选择创建Windows Form Control,它可以是编译成一个 dll 库,您可以在其他项目中使用它。

您应该尝试创建一个Windows Form Control Library.

这是 Windows 窗体控件库的一个很好的示例:https ://www.mindstick.com/Articles/51/creating-and-using-windows-forms-control-library-in-c-sharp-dot-net


推荐阅读