日期:2014-05-18  浏览次数:21039 次

textbox查找和替换
我想实现在 textbox中实现查找和替换功能,在网上看了许多,自己写还是有问题。

我的主窗体为 Form7 我在 查找窗体 上的“查找”按钮的 Click 事件程序为:


 [code=C#][/code] private void button1_Click(object sender, EventArgs e)
  {
  string sr1 = this.textBox1.Text;
  Form7 form7 = new Form7();
  string sr2 = form7.txt1.Text;
  int currpos = form7.txt1.SelectionStart;
  int startIndex = sr2.IndexOf(sr1,currpos);
  if (startIndex == -1)
  {
  MessageBox.Show("没有");
  } 
  if(startIndex >= 0 && startIndex < sr2.Length) 
  { 
  form7.txt1.Select(startIndex ,sr1.Length) ; 
  form7.txt1.Focus() ; 
  startIndex += sr1.Length ; 
  } 
   


  }


但是在 Form7中每次查找时 startIndex=-1 不知道为什么?

------解决方案--------------------
form7 你在button的click事件里面new出来还没show呢,哪来的值?除非你是在 Form7的构造函数里把值写死的。
如果你的意思是点击按钮之前Form7已经存在的话,应该写成这样:
C# code

TextBoxTest form7 = null;
foreach(Form f in Application.OpenForms)
{
    if (f is TextBoxTest)
    {
        form7 = (TextBoxTest)f;
        break;
    }
}
if (form7 != null)
{
    string sr1 = this.textBox1.Text;
        string sr2 = form7.txt1.Text;
        ......
}