Home > Backend Development > C++ > How Can I Efficiently Access Form Controls from Another Form in C#?

How Can I Efficiently Access Form Controls from Another Form in C#?

Susan Sarandon
Release: 2025-01-07 13:36:43
Original
896 people have browsed it

How Can I Efficiently Access Form Controls from Another Form in C#?

Accessing Form Controls from Another Form

In a scenario where you have multiple forms and need to access controls belonging to a different form, seeking efficient methods is crucial. One approach involves creating a setter property in one form and referencing it from the other. However, enhancing this communication further is possible.

Introducing the concept of Singleton forms is one potential solution. However, it may not be the most optimal solution in all circumstances. Instead, consider passing a reference of one form to another.

Sample Implementation:

In this example, the main form (Form1) triggers the opening of another form (Form2). To facilitate communication, Form2 takes the calling form as an argument during its instantiation, providing a reference to its members. This opens up various communication possibilities.

Form1:

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; }
}
Copy after login

Form2:

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;
}
Copy after login

By adopting this approach, communication between forms becomes more flexible, empowering you to access controls and manipulate data as needed.

The above is the detailed content of How Can I Efficiently Access Form Controls from Another Form in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template