
C# Jak se dá najít a nahradit text v richTextBox1?
Jak se dá najít a nahradit text v richTextBox1?
Replace nafunguje
private void btnNahradit_Click(object sender, EventArgs e)
{
int start = 0;
int konec = richTextBox1.Text.LastIndexOf(cbVyhledat.Text);
while (start < konec)
{
richTextBox1.Find(cbVyhledat.Text, start, richTextBox1.TextLength, RichTextBoxFinds.MatchCase);
richTextBox1.SelectionBackColor = Color.Yellow;
start = richTextBox1.Text.IndexOf(cbVyhledat.Text, start) + 1;
//Replace nefunguje
richTextBox1.Text = richTextBox1.Text.Replace(cbVyhledat.Text,
cbNahradit.Text);
}
}
////////////////////////////////////////////////////////////
Anebo jak udělat tady z toho cyklus ať to nahradí vše?
///////////////////////////////////////////////////////////
mujString = richTextBox1.Text;
najit = cbVyhledat.Text.Trim();
nahradit = cbNahradit.Text.Trim();
location = richTextBox1.Text.IndexOf(najit);
if (umisteni == -1)
{
MessageBox.Show("String není", "Zpráva");
}
else
{
while (???????)
{
richTextBox1.Text = mujString.Remove(location, najit.Length).Insert
(location, nahradit);
// Alternativa
/*richTextBox1.Text = mujString.Substring(0, location) + nahradit +
mujString.Substring(location + najit.Length);*/
}
}
Replace určitě funguje.
Tak kde mám chybu
To netuším, zkus poskytnout kompletní kód. Proč tam máš vůbec ten cyklus, nemá žádný smysl.
cyklus tam je aby nahradil všechny vyhledané výrazy
Tohle ale Replace dělá standardně.
dal sem pryč ten cyklus a funguje to
Kompletní kód
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace TextEdit01
{
public partial class oknoProgramu : Form
{
public oknoProgramu()
{
InitializeComponent();
}
private void btnOtevrit_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
richTextBox1.Text = File.ReadAllText(label1.Text);
}
}
private void btnUlozit_Click(object sender, EventArgs e)
{
richTextBox1.SaveFile(label1.Text, RichTextBoxStreamType.PlainText);
}
private void btnNahradit_Click(object sender, EventArgs e)
{
int start = 0;
int konec = richTextBox1.Text.LastIndexOf(cbVyhledat.Text);
while (start < konec)
{
richTextBox1.Find(cbVyhledat.Text, start, richTextBox1.TextLength, RichTextBoxFinds.MatchCase);
richTextBox1.SelectionBackColor = Color.Yellow;
start = richTextBox1.Text.IndexOf(cbVyhledat.Text, start) + 1;
//Replace nefunguje
richTextBox1.Text = richTextBox1.Text.Replace(cbVyhledat.Text,
cbNahradit.Text);
}
}