One solution could be to use a StringCollection
user setting (EDIT: In your comment you're saying that this will not be persisted when closing the application. That's not true, as this is the entire point of using user settings...).
In every line, you need to save the position and the name of a control as a string, for example like
120;140;MyName
When the user adds a new button, create an item in the StringCollection
like so:
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);
}
Then you'd need code that creates the buttons from every item in the StringCollection
by reading each line, extracting the location and name and calling make_book
again (not my new make_BookButtonAndStore
method, as this would double the button).
Note that you may need to create the StringCollection
with the new
keyword before adding the first button.
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
.
In your form's constructor, add the following line:
if (Properties.Settings.Default.ButtonStringCollection == null)
Properties.Settings.Default.ButtonStringCollection = new StringCollection();
Then, add the code I've provided above to create the buttons. Also, in the form's Load
event handler, add something like the following:
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]);
}
}
}