求助:动态创建按钮的文本与功能持久化实现方案
问题描述
我想要保存程序运行时用户创建的按钮文本和自定义按钮功能,目前尝试用Properties.Settings.Default和自定义的ButtonStringCollection集合来实现。我曾考虑用另一个表单输入信息,但最终用了InputBox。现在程序关闭后会“遗忘”所有创建按钮的文本,每次都得重新输入,而且没有机制阻止值被修改。我希望实现这些值的持久化,但不清楚可行的实现机制。
完整代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.Serialization.Formatters.Soap; using System.IO; using System.Collections.Specialized; using Microsoft.VisualBasic; namespace WindowsFormsApplication1 { public partial class Form1 : Form { int x1 = 10; public string name; public Form1() { InitializeComponent(); if (Properties.Settings.Default.ButtonStringCollection == null) Properties.Settings.Default.ButtonStringCollection = new StringCollection(); } private void make_Book(int x, int y) { name = Interaction.InputBox("Enter Name", "", "", 300,300); Form2 form2 = new Form2(); Button book1 = new Button(); // book1.Name = name; book1.Text = name; book1.Height = 50; book1.Width = 70; book1.Location = new Point(44 + x, 19 + y); //book1.Click += new EventHandler(myClickHandler); flowLayoutPanel1.Controls.Add(book1); } private void make_BookButtonAndStore(int x, int y) { make_Book(x, y); Properties.Settings.Default.ButtonStringCollection.Add(String.Format("{0};{1};{2}", x, y, name)); Properties.Settings.Default.Save(); } private void Form1_Load(object sender, EventArgs e) { 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); } } } } private void button1_Click(object sender, EventArgs e) { // Form2 form2 = new Form2(); // form2.Show(); // form2.ShowDialog(); make_BookButtonAndStore(x1 += 80, 20); } private void button2_Click(object sender, EventArgs e) { if (flowLayoutPanel1.Controls.Count > 0) { flowLayoutPanel1.Controls.RemoveAt(0); Properties.Settings.Default.ButtonStringCollection.RemoveAt(0); Properties.Settings.Default.Save(); } else MessageBox.Show("На панеле больше нет кнопок"); } } }
内容的提问来源于stack exchange,提问作者mifus arakiev
相关产品推荐
相关产品推荐

