Search code examples
c#formsc#-4.0c#-3.0instances

Creating a new instance of form1 and change that forms property


In my current project, I am making a sticky-note type application in which the user can have multiple instances open of the same form. However, I was wondering if there was a way in C# where I can create a new instance of form1 however have the new form's title/text/heading to be form2.

If this is achievable, I would like a nudge into the correct direction of how to code that part of my app.

Thanks everyone.

--EDIT--

I realized I forgot to add something important:

I need to be able to calculate how many instances are currently open. From there I will add +1 to the form text.


Solution

  • Try accessing the forms properties from the class:

    MyForm newForm = new MyForm();
    newForm.Show();
    newForm.Text = "Form2";
    

    Or call a method from the current form to set the text:

    // In MyForm
    public void SetTitle(string text)
    {
        this.Text = text;
    }
    
    // Call the Method
    MyForm newForm = new MyForm();
    newForm.Show();
    newForm.SetTitle("Form2");
    

    Hope this helps!

    To check the amount of forms open you could try something like this:

    // In MyForm
    private int counter = 1;
    public void Counter(int count)
    {
        counter = count;
    }
    // Example
    MyForm newForm = new MyForm();
    counter++;
    newForm.Counter(counter);
    

    It may be confusing to use, but lets say you have a button that opens a new instance of the same form. Since you have one form open at the start counter = 1. Every time you click on the button, it will send counter++ or 2 to the form. If you open another form, it will send counter = 3 and so on. There might be a better way to do this but I am not sure.