0

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.

Vlad781
  • 37
  • 1
  • 2
  • 7

2 Answers2

1

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.

matthewr
  • 4,679
  • 5
  • 30
  • 40
  • Yes, thank you for the quick answer. The first method worked perfectly. Just one question. Is there a method which allows me to count the number of total forms my application is running? – Vlad781 Jul 20 '12 at 06:00
  • Application.OpenForms could help you out. Keep this in mind: http://stackoverflow.com/questions/3751554/application-openforms-count-0-always – Rob Angelier Jul 20 '12 at 06:04
0

Use a static field to keep a count of how many instances have been opened, and use it to set the form's caption.

Here's a sketch; if you want different behavior you could skip the OnFormClosed override:

public class TheFormClass : Form
{
    private static int _openCount = 0;

    protected override void OnLoad(EventArgs e)
    {
        _openCount++;
        base.OnLoad(e);
        this.Text = "Form" + _openCount;
    }

    protected override void OnFormClosed(FormClosedEventArgs e)
    {
        _openCount--;
        base.OnFormClosed(e);
    }
}
phoog
  • 42,068
  • 6
  • 79
  • 117