开发者

Move text from one Form RichtextBox to another on another form in c#

I am making a program that allows users to add notes via a separate form for them to be able to add that text written in that form back into the origina开发者_开发百科l form. At the moment i can't move the text written in one form richtextbox to the other richtextbox in the main form. Please Help,

Thanks


Most likely your issue is going to be due to the scope of the richtextbox controls. By default in WinForms when you create a control in a form, it has the scope of Private. This means that the control will not be directly accessible from another form's code. There are several ways around this. The simplest would be to change it to a broader scope in this declaration (Public/Internal) which would than allow you to do something along the lines of this:

richTextBox1.Text = Form2.richTextBox1.Text;

*This assumes your code is in Form1 and your second form is named Form2. Obviously that would need to be changed accordingly.

This is not considered good practice because of potential risks associated with allowing any other section of your program to edit the controls contained on this form. Your ideal solutions for passing information to a form are either via the constructor, a properly scoped method, properly scoped property, or in some cases via an event depending on the type of information and when it can be modified and what it is used for.

Without knowing too many details about your specific case, I would probably recommend using a method because this would be the simplest case.

public void UpdateText(string value) {
   richTextBox1.Text = value;
}

This would allow other forms and controls to call this method which would in turn update the text of the richTextBox.

I will note that none of these examples should be used in production code (I do not show how to handle cross threading issues, or data validation), but I presume from the nature of the question you are doing this more as a learning exercise.


If you want to move a value to new Form you can use Constructor of new form:

public Form2(string text)
{
    textbox1.Text = text;
}

and if you want that new form return a value to current form you can use Property in new form:

public string Value
{
    get
    {
        return textbox1.Text;
    }
}

and in use:

using (var instance = new Form2())
{
    instance.Show();
    returnValue = instance.Value;
}


I assume that you are calling your new form from the main form. In this case you can either use the sender to get the instance or on your form you can refer to the other form via the Parent property and its children if the other form is another child.


Like this:

richTextBox1.Text = richTextBox2.Text;

And if you want to append text then:

richTextBox1.Text += richTextBox2.Text;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜