Accessing controls on other open forms  
Author Message
RRTSReaper





PostPosted: Visual C# General, Accessing controls on other open forms Top

Hi,

Just a quick question. I have multiple forms in my program, and in one case i need to access the controls on one open form from another, which is also open. How would i go about doing this an example would be very helpful.

Regards,

Reaper



Visual C#6  
 
 
cverdon





PostPosted: Visual C# General, Accessing controls on other open forms Top

Hi,

It is not a good idea to create dependency between multiple forms's control. what will happen if the user closes the second form

This does not mean that 2 forms cannot communicate however. To make 2 forms communicate, you have to keep an instance to the form once you opened it and call the public method of the second form. Here's a sample:

public class FormRed : Form

{

FormBlue frmBlue;

public FormBlue FormBlue

{

get { return frmBlue; }

set { frmBlue = value; }

}

private void Form_Load(object sender, EventArgs e)

{

this.BackColor = Color.Red;

}

private void ChangeColorOnOtherForm_Click(

object sender, EventArgs e )

{

if ( frmBlue != null ) {

frmBlue.ChangeColor();

}

}

public void ChangeColor()

{

this.BackColor = Color.Green;

}

}

public class FormBlue : Form

{

FormRed frmRed = null;

private void Form_Load( object sender, EventArgs e )

{

this.BackColor = Color.Blue;

}

private void OpenFormRed_Click(object sender, EventArgs e )

{

if (frmRed==null) {

frmRed.Show();

frmRed.FormBlue = this;

}

}

private void ChangeColorOnOtherForm_Click(

object sender, EventArgs e )

{

if ( frmRed != null ) {

frmRed.ChangeColor();

}

}

public void ChangeColor()

{

this.BackColor = Color.Violet;

}

}

Here you can see that the 2 forms don't acces each other's controls directly: they go through the forms public methods.

Regards,
Charles


 
 
RRTSReaper





PostPosted: Visual C# General, Accessing controls on other open forms Top

thanks, this was very helpful and solved my problem.