Felix Torssell Felix Torssell - 18 days ago 6
C# Question

How to manipulate label of form2 in form3

I am trying to have a button in

Form3
change a label's text in
Form1
and
Form2
.
I have gotten it to work somewhat but in order to have the label change I have to have the mouse click on it. This is my current code in form 1 and 2:

label1.Text = Form3.myNameClass.myName;


and this is code in form 3

public class tournamentNameClass
{
public static string tournamentName;
}

public void button1_Click(object sender, EventArgs e)
{
myNameClass.myName = textBox3.Text;
}


How can I make it so that I dont need to press the label to get it to change?

Jim Jim
Answer

Since you are at the start of learning, I'm not going to go in events and delegates.

My example lets you show how you manipulate a control on Form1 from Form2 directly. You should be able to figure this out for Form3 easily by yourself, and is together a good practice of understanding.

(I want to state that there are many different methods of doing this, I guess this is the easiest one for you to understand as a beginner, as this is the most simplistic approach of all)

Form1 Designer

First we make label1 its modifier to Public (so we can reach it in another class) in the designer like so:

label1 designer

Form1 code behind

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

    private void button1_Click(object sender, EventArgs e)
    {
        // With the keyword "this" we pass in Form1, the current instance we are in
        Form2 form2 = new Form2(this);
        form2.Show();
    }
}

Form2 code behind

private Form1 _form1;

public Form2(Form1 form1)
{
    _form1 = form1;
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    _form1.label1.Text = "lets change the text";
}

We are passing Form1 completely in the constructor, this could easily be the Label1 control alone.

Result

result

Comments