Web Design that taps into the haromny and vision of your dreams.

Using Multiple Forms in C#

Adding additional forms to an application

Written By on in C#

866 words, estimated reading time 4 minutes.

In this tutorial we look at how we can add new forms to our projects and how to access controls on different forms.

There are two different type of multiform applications, those where another form is used as a dialog box, i.e. settings or about, and another where there are multiple forms that can all be accessed at the same time, or switched between, such as Microsoft Word. This is known as Multiple Document Interface. This tutorial deals with the former scenario; we will add a new form to our Notepad Lite application and have it manipulate the contents of the text box. We will look at project scope, namespaces and global variables. The next tutorial will look at converting our single document application to a multiple document interface.

To create a new form in Visual Studio or Visual C# Express, click on the Add New Item icon and select Add Windows Form, or you can right click your project on the Solution Explorer, or select File » New » File... and select Windows Form. This will create a new blank form that will form the basis of an Insert Text box. Go ahead and give the new form a name (frmInsertDateTime) and title (Insert Date/Time). Since we do not want this form to be sizeable or maximised/minimised we can disable these features by setting the FormBorderStyle to FixedDialog and MaximizeBox and MinimizeBox to false.

Create a new form in Visual Studio
Create a new form in Visual Studio

We will also add a listBox (lstFormats) and two buttons (btnInsert and btnClose). Set the form's AcceptButton property to btnInsert and the CancelButton property to btnClose. This will handle the return key and escape key actions.

Next I created a list of date format strings to show in the list box. I declare the list at the top of the class, and add items in the forms constructor, and then when the form is loaded I can iterate through the list and add the items to the list box.

public partial class frmInsertDataTime : Form
{
  List<string> dateFormats = new List<string>();
 
  public frmInsertDataTime()
  {
    InitializeComponent();
 
    dateFormats.Add("{0:d}"); // 08/12/2007
    dateFormats.Add("{0:D}"); // 08 December 2007
    dateFormats.Add("{0:t}"); // 15:27
    dateFormats.Add("{0:T}"); // 15:27:40
    dateFormats.Add("{0:f}"); // 08 December 2007 15:27
    dateFormats.Add("{0:F}"); // 08 December 2007 15:27:40
    dateFormats.Add("{0:g}"); // 08/12/2007 15:27
    dateFormats.Add("{0:G}"); // 08/12/2007 15:27:40
    dateFormats.Add("{0:M}"); // 08 December
    dateFormats.Add("{0:r}"); // Sat, 08 Dec 2007 15:27:40 GMT
    dateFormats.Add("{0:s}"); // 2007-12-08T15:27:40
    dateFormats.Add("{0:u}"); // 2007-12-08 15:27:40
    dateFormats.Add("{0:U}"); // 08 December 2007 15:27:40
    dateFormats.Add("{0:Y}"); // December 2007
  }
 
  private void frmInsertDataTime_Load(object sender, EventArgs e)
  {
    lstFormats.Items.Clear();
    foreach (string format in dateFormats)
    {
      lstFormats.Items.Add(String.Format(format, DateTime.Now));
    }
  }

Note that date formatting is dependent on the system regional settings; the example strings here are from my local locale (en-gb).

Back on our main form (frmMain) we need a way to open this new form. To do this, we must first create an instance of frmInsertDateTime, then call its Show method. Add this code into the dateTimeToolStripMenuItem_Click() method.

frmInsertDateTime frmInsertDateTime = new frmInsertDateTime();
frmInsertDateTime.Show();

Next we need to add a main menu "Insert" with an item titled "Date/Time...". Be sure to name the items correctly and in line with the rest of the menu items created.

The next thing we need to do is assign actions to close the form and to insert the text into the text editor.

On the frmInsertDateTime dialog designer, create methods for btnClose by double clicking it and add the following code.

this.Close();

The code for inserting the text is a little more complex, so we will have a look at that in a minute. When you run the program to test it you will be able to click on the menu item and the form will show with the list box filled with the current date and time in different formats. You can select a date time format and close the date time form.

In order to access the richTextBox control on the main form from within our other form we need to change a few lines of code. Firstly, we need a way to reference the object frmMain rather than the class frmMain, the easiest way is to send the object as a parameter to the constructor and reference that.

In the frmInsertDateTime source we modify the constructor to read as below:

private frmMain theParent;
 
public frmInsertDateTime(frmMain Parent)
{
  InitializeComponent();  
  dateFormats.Add("{0:d}"); // 08/12/2007
...
  dateFormats.Add("{0:Y}"); // December 2007
 
  this.theParent = Parent;
}

Notice the parameter, variable declaration and the assignment. Next we need to create a public property that we can use to access the private control on frmMain.

We need to modify the frmInsertDateTime.Show() line to pass the frmMain object:

frmInsertDateTime.Show(this)

After the frmMain constructor add this property:

public RichTextBox RichEditor 
{ 
  get { return richTextBox1; } 
  set { richTextBox1 = value; } 
}

This will allow us to read and write to the control from another form. Back to the frmInsertDateTime code and we can now add a line to insert the text:

theParent.RichEditor.SelectedText = lstFormats.Items[lstFormats.SelectedIndex].ToString();

Now when you run the program we have a fully functioning custom dialogue box that is able to access a control on another form

Last updated on: Friday 23rd June 2017

 

Comments
Vaidee

Vaidee

I have exactly same problem as James has - does not contain a constructor that takes '0' arguments.

Also the list of date formats does not get populated at all ?
what could be going wrong. I reviewed the code over and over again, but could not fathom why this is not getting populated.

I must however say this is a great tutorial and I have benefitted most.

Do kindly respond as I would like to see this project properly completed.
Thanks a lot.

Reply to Vaidee
matsolof

matsolof

Interesting tutorial for a C# beginner like me.

I understood most of it up to this line:

"Add this code into the dateTimeToolStripMenuItem_Click() method."

What does this mean? Where do I put the code?

I would appreciate an explanation, as would other C# beginners, I think.

Reply to matsolof
Jeff C

Jeff C

The zip file does not contain all the necessary files. It is missing the form named frmInsertDataTime.

Reply to Jeff C
James

James

Hi,
Thanks for these tutorials, very useful newly coming from VB/VBA. I following the above, am having trouble with the line frmInsertDateTime frmInsertDateTime = new frmInsertDateTime(); which gives the error 'WindowsApplication1.frmInsertDateTime' does not contain a constructor that takes '0' arguments.
I cannot see where I have gone wrong - would you be so kind as to send me a zip file of the whole thing?
Kind regards
James

Reply to James

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me