I am learning c#.

I created a new solution. There are two form (MainForm and Form1). I have changed textBox1 on Form1 from private to public.

The following code doesn’t change text of textbox1. Why? also there is no error.

public MainForm()
{
InitializeComponent();
Form1 a = new Form1();
a.Show();
}

void Button1Click(object sender, EventArgs e)
{
Form1 bb = new Form1();
bb.textBox1.Text = "Hello";
}

Also, my application shutdown unexpectedly, when i write the following code.

I have added textbox1 to mainform and changed it from private to public.

On Form1:

public Form1()
{
InitializeComponent();
}

void Button1Click(object sender, EventArgs e)
{
MainForm bb = new MainForm();
bb.textBox1.Text = "Hello";
}

On MainForm:

public MainForm()
{
InitializeComponent();
Form1 a = new Form1();
a.Show();
}
2 Spice ups

Hi,

namespace MainForm
{     

    public partial class frmMainForm : Form
    {

        Form1 a = new Form1();

        public frmMainForm()
        {
            InitializeComponent();
            
        }

        private void frmMainForm_Load(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            a.textBox1.Text = "Hello World";
            a.Show();
        }
    }
}

There is no reason to create so many instances of your form Form1.
Just declare it on the initialisiation of your ‘main’ class.
If you do that, you can access all the public elements of Form1 from anywhere in you class FormMain.

That way it will show the Text in the other form.

Just some advice… name your variables, classes and everything else properly…
for example, all Forms I create i use the prefix ‘frm’ so that would be frmMain, frmCurrTime, frmLogin…
or a textbox would be txtLoginName, txtPassword and so on… you’ll be thankfull if you have a couple of elements on your form/project

1 Spice up

Why would you do that?
You’ll create the form Form1 before you Main Form has been drawn yet…