Search code examples
c#.netwinformsrichtextboxmessage-passing

How to update contents of rich text box in form1 with values coming from form2 without closing form2?


I want to pass values between two Forms (c# both in active states). How can I do it?

I have two forms: Form1 and Form2.

Form1 contains a rich text box and a button. When I click on that button, Form2 should open and a text in rich text box should be sent to a textbox in Form2 and Form1 should remain opened as well being on back of Form2.

Form2 contains a text box and a button where user edits a text in textbox and when user clicks on a button then the edited text should be sent back to the rich text box in Form1 and the Form2 should close/ stay opened and Form1 should highlight the updated text in rich text box.

How can i do it? Can somebody help me to do this with a simple example?


Solution

  • Please changes the field names as you required. Also following code will update the rich text box value concurrently when textfield value in form2 is changed. You may want to do minor changes to trigger it on button change event.

    Add the following method to your From1

    private void SetChildFromValueToParent(object obj, EventArgs args)
        {
            //Read the child form's control value and set it to parent form field
            txtBox.Text = ((TextBox)(obj)).Value.ToString();
        }
    

    Add the following logic to your Form1 button click which opens the Form2

    private void button1_Click(object sender, EventArgs e)
    {
        ChildForm childForm = new ChildForm();
    
        //Find the textbox control in the child form
        Control[] controls = childForm.Controls.Find("textBox", true);
    
        if (null != controls[0])
        {
            //Bind the method in the parent form to child form text control's TextChanged event
            controls[0].TextChanged += new System.EventHandler(SetChildFromValueToParent);
        }
    
        childForm.ShowDialog();
    }
    

    EDIT - Getting value on Button Click

       private void SetChildFromValueToParent(object obj, EventArgs args)
            {
                 //Read the child form's control value and set it to parent form field
                 Form2 from2 = new Form2();
                 string richTextBox.Text =  ((TextBox)form2.Controls["textBox1"]).Text;            
            }