Calling a parent form method in C #

I opened the main form and name the child form of type

     Form4 f = new Form4();
     f.Owner = this;
     f.Show(this);

in form4, the user selects a text file whose contents should be displayed in text field 1 of the main form

I tried something like

Owner.textBox1.Text = "file contents";

but it does not work

+3
source share
6 answers

The best way to link different forms together is through events. Create an event in Form4like FileSelected, and then do something like this:

Form4 f = new Form4();
f.FileSelected += (owner, args) => {
    textBox1.Text = args.FileName;
};
f.Show(this);
+8
source

Also, this is a really bad design, you need to make textBox1 a public member of your main form and make f.Owner the main type of form.

how

 Form4 f = new Form4();
 f.Owner = this;
 f.Show(this);

 // Inside Form4
 MainForm main = this.Owner as MainForm;
 if (main != null) main.textBox1.Text...
+2
source

, Text . :

public partial class MainForm : Form {
    public string ContentDescription {
        set {
            textBox1.Text = value.trim();
        }
    }
}

, , :

public partial class SecondaryForm : Form {
    public MainForm OwnerForm {
        get {
            return (MainForm)this.Owner;
        }
    }

    public void someMethod() {
        OwnerForm.ContentDescription = "file contents";
    }
}

, # . , , . , , , , .

EDIT. parse, , , , Owner .

hlper- , GUI.

+2

Form4 Owner :

var o = (Form1) this.Owner;
o.textBox1.Text = "file contents";

For this to work, the owner must have a type Form1and textBox1in this type, which should be a public member or property.

+1
source

Since Andrew has already given the right solution for event-driven, there is also an available synchronization (or blocking) method:

Form4 f = new Form4;
if(f.ShowDialog() == DialogResult.OK)
{
    textBox1.Text = f.FileName;
}
+1
source

You will need to set the β€œmodifiers” to be at least publicly available so that the properties of the control can have access to it.

alt text http://gabecalabro.com/gabe/Capture.PNG

0
source

Source: https://habr.com/ru/post/1744939/


All Articles