How can I replace text in RichTextBox form another

2019-08-27 07:18发布

So I have a RichTextBox called richTextBox1, in a form named XMLEditor I want to be able to rename any chosen word in all parts of the rich text box with anything I want. (Like find and replace in notepad).

But I want to use another form called Find (It looks like Find & Replace in notepad) to have functions that will replace the words in the richTextBox1 that is in XMLEditor.

The form named Find has a 2 textboxes and 1 button. The first textbox named textBox1 will be used to choose the text you will replace while textBox3 will be what the text is replaced with. And the button button3 will replace the text while clicked.

How can I replace text in a RichTextBox from another form? How can I do this with these forms?

void button3_Click(object sender, EventArgs e)
{
    XMLEditor xmle = new XMLEditor();
    xmle.richTextBox1.Text = xmle.richTextBox1.Text.Replace(textBox1.Text, textBox3.Text);
}

1条回答
ゆ 、 Hurt°
2楼-- · 2019-08-27 08:01

One thing you can do is pass the XMLEditor form as a parameter when constructing Find, and have a public XMLEditor method that can be used for interaction.

interface IFindAndReplace {
    void Replace(String s);
}

public class XMLEditor : IFindAndReplace {
    ...
    public void ShowFindAndReplaceForm() {
        Find findForm = new Find(this);
    }
    public void Replace(String s) {
        //Replace method here
    }
}

public class Find {
    IFindAndReplace parent;
    public Find(IFindAndReplace parent) {
        this.parent = parent;
    }
    public Replace(String s) {
        parent.Replace(s);
        //this will call Replace on the parent form.
    }
}

edited to use interfaces :)

查看更多
登录 后发表回答