[英]how to find and replace text in richtextbox
我正在使用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;
}
}
在這里,我為您提供了有效的答案:
public static void QuickReplace(RichTextBox rtb, String word, String word2)
{
rtb.Text = rtb.Text.Replace(word, word2);
}
private void button1_Click(object sender, EventArgs e)
{
QuickReplace(richTextBox1, textBox1.Text, textBox2.Text);
}
更換richTextBox1
與RichTextBox
Control
,並更換textBox1
和textBox2
與您TextBox
Controls
這將替換在RichTextBox
找到的所有所需文本
我專門針對這種操作編寫了此代碼。
如果您願意,我可以提供代碼來替換另一種形式的文本,例如Notepad 。
我希望這可以幫助你 :)
如果要替換文本中所有出現的搜索詞:
richTextArea.Text = richTextArea.Text.Replace(textBoxSearch.Text, replaceTextBox.Text);
如果要替換搜索的所有實例,請使用:
richTextArea.Text = richTextArea.Text.Replace(textBoxSearch.Text, replaceTextBox.Text);
如果您只想替換一種情況,那么
richTextArea.Text = richTextArea.Text.Remove(index, textBoxSearch.Text.Length);
richTextArea.Text = richTextArea.Text.Insert(index, replaceTextBox.Text);
我添加了兩個按鈕,一個用於將文件的內容加載到富文本框中,另一個用於查找和替換文本,然后將替換后的內容再次寫入文件。
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.