Kaya Suleyman
Kaya Suleyman

Reputation: 85

Access public control from different form C#

I have been struggling with this for a while so I hope you can assist me.

I am attempting to get Form 2 to set the text of my RichboxText (named "sourceCode") located in Form 1 once a user clicks the button on Form 2.

I changed my RichboxText modifier to "public" and I am able to access the control by placing the following in my form 2 button:

private void buttoncreatetable_Click(object sender, EventArgs e)
    {
        GlobalVar.table = "<table" + " align=" + "\"" + alignment.Text + "\"" + " border=" + "\"" + bordersize.Value + "\"" + 
            " cellpadding=" + "\"" + padding.Value + "\"" + " cellspacing=" +
            "\"" + spacing.Value + "\"" + " style=" + "\"" + "width:" + width.Value + "px;"
            + " height:" + height.Value + "px;" + "\"" + ">" + Environment.NewLine + "<tbody>"; //end tbody, table, tr and td

        Form1 form1 = new Form1();
        form1.Show();
        form1.sourceCode.SelectedText = GlobalVar.table;

However the result of this code is that although it inserts the text into the Richbox, it creates an entirely *new *instance of Form 1 and does it, as opposed to inserting the text into the Richbox of the original instance of Form 1 without creating a new one.

I suspect the reason is because of this code: Form1 form1 = new Form1(); which instantiates a new copy of Form1. But without doing this there is no way of accessing Form 1 control properties easily.

Please assist me. Thank you in advance!

Upvotes: 1

Views: 676

Answers (2)

Tarec
Tarec

Reputation: 3255

Just add a Form1 reference property in your Form2 class.

public Form1 form1;

And assign it in your Main method (I assume you're initializing them there).

Form1 form1 = new Form1();
Form2 form2 = new Form2();
form1.Show();
form2.Show();
form2.form1 = form1;

edit: Also, you should not change internal elements of one form from another. It breaks basic OO programming principles. Instead write yourself a method in Form1

void UpdateSelectedText(string updatedText)
{
    sourceCode.SelectedText = updatedText;
}

and then call it from form2

form1.UpdateSelectedText("Some new text");

Upvotes: 1

Lee White
Lee White

Reputation: 3729

Form firstForm = Application.OpenForms["FormName"];

The OpenForms property is a very basic property that lists the forms that are currently open. Just use the form's name as ID.

Click here for OpenForms documentation.

Upvotes: 1

Related Questions