Controling Controls from other Forms

Hello!

I have to Windows Forms - Main.cs and Menu.cs

I would like to control the richTextBox control from the Menu.cs Windows Form. The richTextBox control is located on Main.cs. How can I do that: For example how can I execute the "copy" method of the richTextBox which is on Main.cs from Menu.cs.

Please help!

Thx

Matt


Answer this question

Controling Controls from other Forms

  • sugrhigh

    Thanks, but how can I make the richtextbox static

    Im just starting out with C#.

    Thx,

    Matt

  • cisfreak2

    When you create the form its create a partial class for that now go to the form right click on its Initialize() and go to defination at the end of file there will declaration of all controls you can find your richtext box there now modify it to be static.

  • John CHLee

    Hi,

    Two ways!

    Either make the richtextbox static and access it directly from
    the main form like this  Main.richtextBox. ***

    You can also get reference of Main form in the Menu form then use that reference to access the richtext box.

    when creating instance of menu  form from main form pass it main form like this 
    menu frmmneu=new menu(this);

    and in the menu form you can get it from constructor and set all class variable to hold...

    main frmmain;
    menu(main frm)

    {

     frmmain=frm;

    }

    Now you can use ,....

    frm.richtextBox.****

    Hope this help.

     



  • moorpipe

    One more thing: What if I created an instance of the RichTextBox in Designer view. How can I make that static

    Matt

  • Can-Ann

    Hi Mateusz Rajca ,

    Here is the sample code.
    Where Form1 can be consider as your main form and Form2 can be considered as menu form.

    Form1-Having Rich Text Box


    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Text;

    using System.Windows.Forms;

    namespace RTBDEMO

    {

    public partial class Form1 : Form

    {

    public static RichTextBox rtb = new RichTextBox();

    public Form1()

    {

    InitializeComponent();

    rtb.Dock = DockStyle.Fill;

    this.Controls.Add(rtb);

    }

    }

    }

    Form 2 – Accessing Text Box


    using
    System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Text;

    using System.Windows.Forms;

    namespace RTBDEMO

    {

    public partial class Form2 : Form

    {

    public Form2()

    {

    InitializeComponent();

    Form1.rtb.Copy();

    }

    }

    }



    Hope this help.



  • Controling Controls from other Forms