Interaction Between Forms - How to Change a Control of a Form from Another Form

Interaction between forms — How to change a control of a form from another form?

Form in Windows Forms is a class like other C# classes. The way of communicating between forms are the same as classes. You can consider this options when communicating between classes:

Manipulate second Form from first Form

  • You can add suitable parameters to the constructor of the second form. Then you can pass values to the constructor when creating an instance of the second form. In the second form store parameters in member fields and use them when you nees.

  • You can create public property or method in the second form and set those properties after creating an instance of the second form. This way you can use them when you need in the second form. This option is not limited to passing values when creating the second form. You can even use that property during the execution of second Form. Also it's useful for getting a value from it.

  • As another option you can make the control which you want to manipulate it public and this way you can access to it from other form. Using a method is a more recommended way of doing this.

Manipulate first Form from second form

  • You can create a public method or property in first form and pass an instance of the first form to second form. Then using that method/property on the passed instance, you can manipulate the first form.

  • You can create an event in second form and after creating an instance of second form subscribe for it in first form and put the code for changing the form in the handler. Then it's enough to raise the event in second form.

  • You can define a public property of type Action or some other delegate type in second form and then after creating an instance of second form, assign the property using a custom action. Then in second form, it's enough to invoke the action when you need to manipulate first form.

  • Also here you can make a control of first form to be public and then if you pass an instance of the first form to the second form, you can manipulate the control. It's recommended to use other solutions. It's like creating public property or method, but a method which performs specific task on the control is better that exposing the whole control. But you may need this solution some times.

Here are some useful examples about above solutions.

Manipulate second Form from first Form

Example1 - Using constructor of second Form

Use this example when you need to pass some data to second form, when creating the second form.

public partial class Form2 : Form
{
int selectedValue;
public Form2(int value)
{
InitializeComponent();
selectedValue = value;
}
private void Form2_Load(object sender, EventArgs e)
{
//Load data
this.comboBox1.DataSource = new MyDbContext().Categories.ToList();
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedValue = selectedValue;
}
}

Then in your first form, it's enough to pass the value to Form2 when you create a new instance of it:

var value = 2; // Or get it from grid
var f = new Form2(value);
f.ShowDialog();

Example2 - using public Property or Method of second Form

Use this example when you need to pass some data to second form, when creating or even after creation of second form.

public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string SomeValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}

Then in your first form, it's enough to pass the value to Form2 when you need, after creating Form2 or whenever you need to set value of textBox1 on Form2:

var f = new Form2(); //value is not needed here
f.SomeValue = "some value";
f.Show();
//...
f.SomeValue = "some other value";

Example 3 - Making a Control of Second form public

Use this example when you need to change a property of a control on second form, when creating or even after creation of second form. It's better to use public property or method instead of exposing whole control properties.

In your Form, at designer, select the control and in Properties window set the Modifiers property to Public. Also make sure the GenerateMember property is true. Then you can simply access this control using its name from outside of the Form.

var f = new Form2();
f.textBox1= "some value";

Manipulate first Form from second form

Example 4 - Create public Method or Property in first Form and pass an instance of First Form to constructor of second Form

Use this example when you need to change first Form from second Form.

In your Form1, create a property of a method that accepts some parameters and put the logic in it:

public void ChangeTextBox1Text(string text)
{
this.textBox1.Text = text;
}

Then create a constructor in Form2 which accepts a parameter of type Form1 and keep the passed value in a member field and use it when you need:

Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.ChangeTextBox1Text("Some Value");
}

Now when creating Form2 you should pass an instance of Form1 to it:

var f = new Form2(this);
f.Show();

Example 5 - Using event of second Form in first Form

Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.

Example 6 - Injection an Action in second Form

Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.

Example 7 - Making a Control of first form public

In this solution you need to make a control in first form public, like example 3. Then like example 4 pass an instance of the first form to second form and keep it in a field and use it when you need. Using a public method or property is preferred.

Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.textBox1.Text = "Some Value";
}

when creating Form2 you should pass an instance of Form1 to it:

var f = new Form2(this);
f.Show();

How to access a form control for another form?

Making them Singleton is not a completely bad idea, but personally I would not prefer to do it that way. I'd rather pass the reference of one to another form. Here's an example.

Form1 triggers Form2 to open. Form2 has overloaded constructor which takes calling form as argument and provides its reference to Form2 members. This solves the communication problem. For example I've exposed Label Property as public in Form1 which is modified in Form2.

With this approach you can do communication in different ways.

Download Link for Sample Project

//Your Form1

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}

public string LabelText
{
get { return Lbl.Text; }
set { Lbl.Text = value; }
}
}

//Your Form2

public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}

private void Form2_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{
this.mainForm.LabelText = txtMessage.Text;
}
}

alt text

(source: ruchitsurati.net)

alt text

(source: ruchitsurati.net)

Changing text in one form, from another form

There are several way to do this here 2 examples

  1. This example use references whitout any use of events

    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
    var frm = new Form2(this);
    frm.Show();
    }

    }

here the Form2 is created passing the Form1 as parameter

 public partial class Form2 : Form
{
Form1 _parent;
public Form2(Form1 parent)
{
_parent = parent;
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
var lbl = (Label)_parent.Controls.Find("label1", false).First();
lbl.Text = "new text";
_parent.Update();
}
}

Than the Form2 use that for set the value wanted.


  1. This example use events

     public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
    var frm = new Form2();
    frm.UpdateLabelEvent += Frm_UpdateLabelEvent;
    frm.Show();
    }

    private void Frm_UpdateLabelEvent(string str)
    {
    label1.Text = str;
    }
    }

and here the code of Form2

 public partial class Form2 : Form
{

public event Action<string> UpdateLabelEvent;

public Form2()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
UpdateLabelEvent("new string value");
}
}

How can I change the background of the a form from a second form?

You can set the Form 2's owner to Form1. Then access it's properties that way.

Form 1

private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.ShowDialog(this);
}

Form 2

private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = (Form1)this.Owner;
frm1.TransparencyKey = Color.Turquoise;
frm1.BackColor = Color.Turquoise;
}

Using The Controls Of One Form Into Another

Depending on how you launch the second form you can either assign a member object in Form2 that references Form1 or if you are using an MDI interface there is a forms collection from which you can retrieve a reference to your Form1.

For example, you could have the following code in your Form2 class:

public partial class Form2 : Form
{
public Form1 LaunchOrigin { get; set; }
// and so on

Now you can assign the LaunchOrigin member when you launch Form2. Here is an example:

Form2 newForm = new Form2();
newForm.LaunchOrigin = this;
newForm.Show();

You now have access to Form1 and all its members. Here is a simple example of that:

    private void Form2_Load(object sender, EventArgs e)
{
this.Text = LaunchOrigin.Text;
}

You must remember that controls are declared as private so you won't have direct access to them. You could write a property on Form1 that referenced that control but this is most often a bad idea. For the sake of completeness, however, here is some code that you could use to expose a button on Form1:

public partial class Form1 : Form
{
public Button theButton;
public Form1()
{
InitializeComponent();
theButton = button1; // where button1 is what I dragged on
}
// and so on

Although what you're asking is relatively easy to accomplish, it puts you on the road to some brittle application structure. Think hard about what it is you're trying to expose between forms, perhaps it deserves to be a distinct type that you can bind to both forms so that once you change the underlying type, you change the representation on both.

Switching between forms (closing one form, then opening another)

You could add two panels to a single form, each of which contains the controls you would otherwise have added to one of the two forms. Then switch between the panels by changing their visibility or Z-order. This is slightly tricky in the Windows Forms Designer because you'll have to design the two panels, then position them in the same spot on the containing form.

As @ryanyuyu points out, you can set the Dock property to DockStyle.Fill and switch which panel is on top using Control.BringToFront or Control.SendToBack(). This is also a decent way to interact with the two panels in the designer, as you can switch which is on top from a context menu option.

Passing Values from one Form to another Form in a Button click

Actually I have an object to pass. So I did this

in form1-->

private void btnOpenF2_Click(object sender, EventArgs e)
{
new Form2(this).Show();
}

in form2-->

public partial class Form2 : Form
{
Form1 a;
public Form2(Form1 b)
{
a = b;
InitializeComponent();

}
private void button1_Click(object sender, EventArgs e)
{
string g;
g = textBox1.Text;


a.set(g);
this.Close();
}
}

Interaction between two user controls in windows form application

One option is passing UserControlA instance to UserControlB's constructor.

public partial class UserControlB: UserControl
{
UserControlA userControlA;

public UserControlB(UserControlA ucA)
{
userControlA = ucA;
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
string myString = userControlA.TexBoxText;
}
}


Related Topics



Leave a reply



Submit