c# - 替换和替换所有 c# windows 窗体

标签 c# windows forms

我在替换找到的文本时遇到问题。到目前为止,我的代码已尝试进行替换,但似乎无法正常工作。我知道我需要使用插入方法,但不确定要在其中放入什么。

到目前为止,这是我的代码:

RichTextBox frm1TB = ((Form1)this.Owner).txtDisplay;

foundAt = frm1TB.Text.IndexOf(replacingRichText.Text);

if (foundAt == -1)
{
    MessageBox.Show("Not Found");
}
else
{
    frm1TB.Text = frm1TB.Text.Replace(searchText.Text, replacingRichText.Text);
    frm1TB.Text.Insert();
    frm1TB.SelectionStart = foundAt;
    frm1TB.SelectionLength = searchText.TextLength;
}

我在 form1 上有 1 个 richtextbox,然后在 form 2 1form 上有 2 个文本框来查找和查找下一个称为 searchText 的框和 2 个用于替换和替换下一个称为 replacingRIchText 的框。

最佳答案

您可能必须以相反的顺序替换这些字符串,因为一旦您替换了一个字符串,您的索引和长度就会不同。

此外,对于您的代码,我认为您需要将其更改为如下内容:

//frm1TB.Text = frm1TB.Text.Replace(searchText.Text, replacingRichText.Text);
//frm1TB.Text.Insert();

frm1TB.SelectionStart = foundAt;
frm1TB.SelectionLength = searchText.TextLength;
frm1TB.SelectedText = replacingRichText.Text;

这是一个简单的例子(根据需要重构):

private void ReplaceText(string findText, string replaceText) {
  int index = frm1TB.Text.Length - 1;
  index = frm1TB.Text.LastIndexOf(findText, index);
  while (index > -1) {
    frm1TB.SelectionStart = index;
    frm1TB.SelectionLength = findText.Length;
    frm1TB.SelectedText = replaceText;
    index = frm1TB.Text.LastIndexOf(findText, index);
  }
}

关于c# - 替换和替换所有 c# windows 窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8271218/

相关文章:

c# - 在哪里安全地存储来自 Windows 服务的数据?

c - 存储在注册表中的字符串值如何不以 null 结尾?

windows - 在 Windows 上初始化 PostgreSQL DB 时出现拒绝访问错误

C# 2005 : Remove icon from the form's title bar

php - 使用 Oauth 发布推文

c# - 调试:附加到在 cmd.exe 中运行的控制台应用程序的进程

c# - 创建邮件发件人对象

c# - Resharper — 修复多个问题

windows - 如何在 Qt 中的弹出窗口小部件上创建平滑的圆角

javascript - "Submit is not a function"在没有其他提交输入的动态创建表单中的 Firefox 错误