how to send message from form2 to form1

N

nadir b

hi
I don't know how to change for exemple a form1 caption text from form2
don't forget that form2 has created from form1
I want sample code with c#
 
G

Guest

hi Nadir

Follow this.

in the form1 class declare put this statement.

public static Form1 staticVar = null;

i.e it shoudl look like the code below

public class Form1 : System.Windows.Forms.Form
{
public static Form1 myform1 = null;
................ otther code....


assuming that you are trying to open form2 in a button click event in Form1
... write the following code (openform2 is a button in form1)

private void openform2_Click(object sender, System.EventArgs e)
{

myform1 = this;

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

}


Now in Form2 you can refer to this static Variable in teh following way

assuming you want to set teh caption of Form1 in a button click event in
Form2. (changeForm2Caption is a button in form2)

private void changeForm2Caption_Click(object sender, System.EventArgs e)
{
Form1.myform1 .Text = "test";
}


The above code will change the caption of form1.

hope this helps

cheers

pradeep TP
 
G

Guest

in the code given by me please read the code

public static Form1 staticVar = null;

as

public static Form1 myform1= null;

i have wrongly typed staticVar in place of myform1

pradeep TP
 
Q

QWERTY

Why dont you just pass a reference of form1 to form2 then use it
within form2.

e.g public class Form2: System....
{
public Form frm;

private void changeForm1Caption()
{
frm.Text = "New caption";
}
}

public class Form1: System...
{
onclick_event()
{
Form2 f = new Form2();
f.frm = this;
f.Show();
}
}
 
D

Dale Preston

Or set the default Form2 parameterless constructor to be private so it can't
be instantiated. Create a new constructor:

// a Form1 field for the Form2 class
private Form1 form1;

// The new Form2 constructor takes a Form1 parameter
public Form2(Form1 frm1)
{
// the rest of your custructor code)
}

// a method that references the form1 field
private void someMethod(string newCaption)
{
form1.Text = newCaption;
}

// and in your Form1, when you create Form2:
Form2 form2 = new Form2(this);

Dale Preston
MCAD, MCDBA, MCSE
 
D

Dale Preston

I left a line out of the new Form2 constructor. Here's how it should have
read:

// The new Form2 constructor takes a Form1 parameter
public Form2(Form1 frm1)
{
this.form1 = frm1; // this is the line I left out.
// the rest of your custructor code)
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top