我正在处理一个C# windows窗体,它执行以下操作:
我有一个显示文本文件内容的RichTextbox
。
我设法构建了一个带有搜索按钮的搜索框,供用户在此文件中搜索特定文本。但是,我还想创建一个查找文本框和按钮,以允许用户将找到的文本替换为他/她在文本框中输入的新文本,然后单击替换按钮。我该如何替换文本?...谢谢。
以下是搜索文本的代码:
private void buttonSearch_Click(object sender, EventArgs e)
{
int index = 0;
var temp = richTextArea.Text;
richTextArea.Text = "";
richTextArea.Text = temp;
while (index < richTextArea.Text.LastIndexOf(textBoxSearch.Text))
{
richTextArea.Find(textBoxSearch.Text, index, richTextArea.TextLength, RichTextBoxFinds.None);
richTextArea.SelectionBackColor = Color.Yellow;
index = richTextArea.Text.IndexOf(textBoxSearch.Text, index) + 1;
}
}
发布于 2018-09-05 03:00:05
如果要替换文本中所有出现的搜索词:
richTextArea.Text = richTextArea.Text.Replace(textBoxSearch.Text, replaceTextBox.Text);
发布于 2018-09-05 03:26:20
我添加了两个按钮,一个用于将文件内容加载到富文本框中,另一个用于查找和替换文本,并将替换的内容再次写入文件。
private void Load_File_Contents_Click(object sender, EventArgs e)
{
try
{
//Below code will read the file and set the rich textbox with the contents of file
string filePath = @"C:\New folder\file1.txt";
richTextBox1.Text = File.ReadAllText(filePath);
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
private void ReplaceAndWriteToFile_Click(object sender, EventArgs e)
{
try
{
string filePath = @"C:\New folder\file1.txt";
//Find the "find" text from the richtextbox and replace it with the "replace" text
string find = txtFind.Text.Trim(); //txtFind is textbox and will have the text that we want to find and replace
string replace = txtReplace.Text.Trim(); //txtReplace is text and it will replace the find text with Replace text
string newText = richTextBox1.Text.Replace(find, replace);
richTextBox1.Text = newText;
//Write the new contents of rich text box to file
File.WriteAllText(filePath, richTextBox1.Text.Trim());
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
https://stackoverflow.com/questions/52172198
复制相似问题