passing data between 3 windows forms in visual studio using C#

后端 未结 5 1810
无人及你
无人及你 2021-01-27 03:23

I have a windows application which has 3 forms : Form1,2,3. I want to send text of a textbox from form2 to form1 and then that same text from for

5条回答
  •  温柔的废话
    2021-01-27 03:41

    That error is thrown because Form3 has no default Constructor anymore since you defined one with a string parameter. you need to create a default Constructor like this public Form3(){}.

    But Instead of doing all this mess you can handle events of you both forms. Like if Form1 is the main Form then something like this can be done:

    In Form1

    public string textFromForm2 = string.Empty;
    private void openform3_Click(object sender, EventArgs e)
    {
        Form3 f3 = new Form3();
        f3.Controls["received_from_form1_textbox"].Text = textFromForm2 ;
        f3.Show();
    }
    
    private void OPENFORM2_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        //I am binding the event to a handler which will save text
        //you should check for null for f2.Controls returned any thing or not, i am leaving it for now
        f2.Controls["send_to_form1_button"].Click += (s,e)=>{
                     txtFromForm2 = f2.Controls["form2_textbox"].Text;
              };
        f2.Show();
    }
    

    Update

    if you don't want to use Lambadas then bind events like this:

    First you will need a reference to the Form2 so declare in your class like this:

    Form2 f2;
    

    then bind the event (in place of the lambada i have given before)

    f2.Controls["send_to_form1_button"].Click  += new Eventhandler(click_handler);
    

    then somewhere in Form1 class:

    protected void click_handler(object sender, EventArgs e)
    {
         if(f2 != null)
             txtFromForm2 = f2.Controls["form2_textbox"].Text;
    }
    

    similarly for Form3.

提交回复
热议问题