I am trying to make a find, find next function for my program, which I did manage to do with this code:
int findPos = 0;
private void button1_Click(object sender, EventArgs e)
{
try
{
string s = textBox1.Text;
richTextBox1.Focus();
findPos = richTextBox1.Find(s, findPos, RichTextBoxFinds.None);
richTextBox1.Select(findPos, s.Length);
findPos += textBox1.Text.Length;
//i = richTextBox1.Find(s, i + s.Length, RichTextBoxFinds.None);
}
catch
{
MessageBox.Show("No Occurences Found");
findPos = 0;
}
}
And it works great in form1 but if I use this code and try to call it from form2 It doesn’t do anything:
//Form1
public void FindNext()
{
try
{
this.Focus();
Form2 frm2 = new Form2();
string s = frm2.textBox1.Text;
richTextBox1.Focus();
findPos = richTextBox1.Find(s, findPos, RichTextBoxFinds.None);
richTextBox1.Select(findPos + 1, s.Length);
findPos += textBox1.Text.Length;
}
catch
{
MessageBox.Show("No Occurences Found");
findPos = 0;
}
}
//Form2
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.FindNext();
}
Does any one know why this is?
Thanks,Tanner.
I think you may be confused in how you reference
Form1andForm2from each other.Calling
new Form()andnew Form2()create references to new instances ofForm1andForm2, they don’t reference the forms that are already open. You need to get the references for the existing instances.Assuming that
Form1is the main form for your application and it creates and showsForm2, you can either add a property toForm2that represents the instance ofForm1that created it, or you can appropriate theOwnerproperty for this purpose (I’d recommend that).In your code on
Form1that showsForm2initially (not in the code you have above), callfrm2.Show(this)instead of justfrm2.Show(). This will set theOwnerproperty of yourForm2instance equal to thinstance ofForm1that opened it.Then change your button code for
Form2to this:This will make you reference the existing form rather than a new one, which is what you want.
As far as the
FindNextfunction goes, you have two choices: either you can hold on to the reference ofForm2(though you probably want to do this anyway) and access the text directly, or you can changeFindNextto take a string (this is what I’d recommend).Then change the call to
frm1.FindNext()onForm2tofrm1.FindNext(textBox1.Text):