我建立一个记事本。我有一个查找和替换形式。当我单击窗体打开按钮,用户给出了两个文本框两个输入并按下一个按钮。然后从主模的RichTextBoxes应该接受修改。

这里的FindAndReplace形式的形式:

private void btnReplaceAll_Click(object sender, EventArgs e)
        {
            string findMe = txtFind.Text;
            string replaceMe = txtReplace.Text;
            Form1 f1 = new Form1();
            f1.MainText.Replace(findMe, replaceMe);
            //this.Hide();
        }

问题是它不工作..我得到的线f1.MainText.Replace(findMe, replaceMe);一个NullReferenceException 任何想法?

有帮助吗?

解决方案

下面创建形式的新实例:

Form1 f1 = new Form1();

所有属性都被初始化为默认值(即,字符串为空)。接下来,您尝试调用 Replace MainText属性,该属性是方法null,你会得到异常:

f1.MainText.Replace(findMe, replaceMe);

您需要先初始化这个属性:

f1.MainText = "blablabla";
f1.MainText = f1.MainText.Replace(findMe, replaceMe);

更新:

当创建FindAndReplace形式你可以传递给它的构造文本的当前值:

public class Form1 : Form
{
    protected void FindAndReplace_Click(object sender, EventArgs e) 
    {
        var findAndReplaceForm = new FindAndReplaceForm(MainText.Text);
        findAndReplaceForm.ShowDialog();
        MainText.Text = findAndReplaceForm.NewText;
    }
}

public class FindAndReplaceForm : Form
{
    private readonly string _originalText;

    public FindAndReplaceForm(string originalText)
    {
        _originalText = originalText;
    }

    public string NewText 
    { 
        get 
        {
            return (_originalText ?? string.Empty).Replace(findMe, replaceMe);
        }
    }
}

其他提示

您查找和替换形式必须了解你的主要形式。你正在做它的方式,你正在创建一个全新的主要形式,这将在正文区域没有文字。当您创建的查找和替换形式,你应该通过你的父窗体,甚至只是正文,到查找和替换形式,然后搜索从刚刚通过的形式主要形式的文本。

您想类似如下:

public class FindAndReplaceForm
{
    private Form1 MainForm;

    public FindAndReplaceForm(Form1 parentForm)
    {
        this.MainForm = parentForm;
        //The rest of you constructor here
    }

    private void btnReplaceAll_Click(object sender, EventArgs e)
    {
        string findMe = txtFind.Text;
        string replaceMe = txtReplace.Text;

        //The following line will search the parent form
        this.MainForm.MainText.Replace(findMe, replaceMe);
        //this.Hide();
    }
}

您可以在您的Program类添加静态形式引用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        public static Form1 F1 { get; set; }
        public static Form2 F2 { get; set; }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Form1 = new Form1();
            Form2 = new Form2();

            Application.Run(Form1);
        }
    }
}

然后,不受任何形式的在应用程序中,你就可以使用Program.Form1Program.Form2作为一个已经实例化的参考。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top