0

I would like to know, in my form1 i have a textbox and button. Wheres in form2 i have a button. this is a sample. In my form1 i have a method called as enabledTextBox. When i click in my form1 button it will direct me to form2 via showDialig whereas when i click the button in form2 it should set the textbox property via calling the method enabledTextBox and exit the form 2. The problem is when i click the form2 exist without setting the value of textbox in form1 as set in form1 button click event. I would like to execute when the button clicks. below are my codes

Form1.cs

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


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

    }

    public void enableTextBox(Boolean isEnabled)
    {
        textBox1.Enabled = isEnabled;
    }
}

Form2.cs

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


    private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        f1.enableTextBox(true);
        this.Close();
    }
}

can i know hwre is my error is and the mistake i am doing

Programmer
  • 39
  • 7
  • 2
    You're creating a new `Form1` instead of calling a method on the existing one. – BJ Myers Apr 24 '16 at 16:24
  • so how is it possible to solve as i need to pass the values, this is sampel as my original project is more complicated thats why i made it simple from this i will be understanding and apply it to my project – Programmer Apr 24 '16 at 16:25
  • 1
    You really need to understand what an instance of a class is. You should pass the instance of the form1 to the form2 and use that instance to call your enableTextBox. A lot of duplicates exist in the related column – Steve Apr 24 '16 at 16:27
  • thanks, i read the post, but still kind of confuse. is it possible to help me out with this. i understand roughly but how will it pass the enable of true still kind of confused – Programmer Apr 24 '16 at 16:29
  • Try to explain what the answer in the duplicates does. When creating the Form2 INSTANCE (ie _f2 = new Form2()_ where f2 is the instance) he passes the _this_ keyword who represents the instance of the calling form. This instance is saved in a global variable inside the Form2 class code. When the time is right he doesn't create a new INSTANCE of Form1 (IE no _f1 = new Form1()_) but uses the instance stored in the global variable inside the Form2 class. Do the same. – Steve Apr 24 '16 at 16:35
  • thanks, i try and understand. – Programmer Apr 24 '16 at 16:44
  • sorry for troubling all of u. i got it now and knows how it needs to be worked – Programmer Apr 24 '16 at 17:13

0 Answers0