English 中文(简体)
如何在Windows窗体中保存在运行时创建的控件
原标题:How I can save controls created in run time in Windows Forms
  • 时间:2012-05-24 14:35:06
  •  标签:
  • c#
  • winforms

这是我的密码

private void make_Book(int x, int y, string name)
{
    #region Creating Book

    // this code is initializing the book(button)
    Button book1 = new Button();
    Image img = button1.Image;
    book1.Image = img;
    book1.Name = name;
    book1.Height = img.Height;
    book1.Width = img.Width;
    book1.Location = new Point(44 + x, 19 + y);            
    book1.Click += new EventHandler(myClickHandler);
    groupBox1.Controls.Add(book1);

    #endregion            
}

每次我点击按钮时,这段代码都会生成一个按钮,现在我想保存创建的按钮及其属性,以便它们可以在每次应用程序启动时出现。。

用C#visual studio 2010编写。。。

最佳回答

一种解决方案是使用StringCollection用户设置编辑:在你的评论中,你说这在关闭应用程序时不会持久。这不是真的,因为这是使用用户设置的全部意义…)。

在每一行中,您都需要将控件的位置和名称保存为字符串,例如

120;140;MyName

当用户添加一个新按钮时,在StringCollection中创建一个项目,如下所示:

private void make_BookButtonAndStore(int x, int y, string name)
{
    make_Book(x,y,name);

    Properties.Settings.Default.ButtonStringCollection.Add(String.Format("{0};{1};{2}", book1.Location.X, book1.Location.Y, book1.Name));
    Properties.Settings.Default.Save();
}

private void make_Book(int x, int y, string name)
{
    // this code is initializing the book(button)
    Button book1 = new Button();
    Image img = button1.Image;
    book1.Image = img;
    book1.Name = name;
    book1.Height = img.Height;
    book1.Width = img.Width;
    book1.Location = new Point(44 + x, 19 + y);            
    book1.Click += new EventHandler(myClickHandler);
    groupBox1.Controls.Add(book1);
}

然后,您需要从StringCollection中的每个项目创建按钮的代码,方法是读取每一行,提取位置和名称,并再次调用make_book而不是我的新make_BookButtonAndStore

请注意,在添加第一个按钮之前,您可能需要使用new关键字创建StringCollection

EDIT
To explain how to create such a setting: Go to your project properties to the "Settings" tab. Create a new setting named ButtonStringCollection, select type System.Collections.Specialized.StringCollection and scope User.

在表单的构造函数中,添加以下行:

if (Properties.Settings.Default.ButtonStringCollection == null)
    Properties.Settings.Default.ButtonStringCollection = new StringCollection();

然后,添加我上面提供的代码来创建按钮。此外,在sLoad事件处理程序的表单中,添加以下内容:

foreach (string line in Properties.Settings.Default.ButtonStringCollection)
{
    if (!String.IsNullOrWhitespace(line))
    {
        // The line will be in format x;y;name
        string[] parts = line.Split( ; );
        if (parts.Length >= 3)
        {
            int x = Convert.ToInt32(parts[0]);
            int y = Convert.ToInt32(parts[1]);

            make_Book(x, y, parts[2]);
        }
    }
}
问题回答

当您调用make_Book方法时,您可以将输入参数保存到数据库或应用程序当前使用的其他存储中。当应用程序启动时,您可以通过调用make_Book方法加载所有按钮,并将值保存在应用程序存储中。

这是一个如何保存加载xml的示例。

public static void Save(string x, string y, string name)
    {
        if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\appName"))
        {
            Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\appName");
        }


        XmlDocument xmlDocument = new XmlDocument();

        string xml = string.Format(@"<?xml version= 1.0  encoding= utf-8 ?><button><x>{0}</x><y>{1}</y><name>{2}</name></button>", x, y, name);

        xmlDocument.LoadXml(xml);

        xmlDocument.Save(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\appName\button.xml");
    }

    public static Dictionary<string,string> Load()
    {
        string address = "";

        if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\appName\button.xml"))
        {
            return new Dictionary<string,string>(){{"x",""},{"y",""},{"name",""}};
        }

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\appName\button.xml");

        XmlNode button = xmlDocument.GetElementsByTagName("button").Item(0);

        XmlNode nameNode = button.SelectSingleNode("name");
        XmlNode xNode = button.SelectSingleNode("x");
        XmlNode yNode = button.SelectSingleNode("y");

        return new Dictionary<string, string>() { { "name", nameNode.InnerText }, { "x", xNode.InnerText }, { "y", yNode.InnerText } };
    }




相关问题
Bring window to foreground after Mutex fails

I was wondering if someone can tell me what would be the best way to bring my application to the foreground if a mutex was not able to be created for a new instance. E.g.: Application X is running ...

How to start WinForm app minimized to tray?

I ve successfully created an app that minimizes to the tray using a NotifyIcon. When the form is manually closed it is successfully hidden from the desktop, taskbar, and alt-tab. The problem occurs ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

Handle DataTable.DataRow cell change event

I have a DataTable that has several DataColumns and DataRow. Now i would like to handle an event when cell of this DataRow is changed. How to do this in c#?

Apparent Memory Leak in DataGridView

How do you force a DataGridView to release its reference to a bound DataSet? We have a rather large dataset being displayed in a DataGridView and noticed that resources were not being freed after the ...

ALT Key Shortcuts Hidden

I am using VS2008 and creating forms. By default, the underscore of the character in a textbox when using an ampersand is not shown when I run the application. ex. "&Goto Here" is not ...

WPF-XAML window in Winforms Application

I have a Winforms application coded in VS C# 2008 and want to insert a WPF window into the window pane of Winforms application. Could you explain me how this is done.