Reputation: 1252
I am making a copy of a Windows Notepad and I'm stuck at "FIND" function. Honestly I have no clue how to make it. I've been searching for a while and everyone suggests RichTextBox because it has implemented find function but the point is i need to make it using textbox.
So I've made new form, connected it with main form. I made class which looks like:
public bool FindAndSelect(string TextToFind, bool MatchCase, bool UpDown)
{
}
But I don't know what to write in it to work. I've made find button in find form with function
if (((fNotepad)this.Owner).FindAndSelect(this.textBoxFind.Text, this.rbUpDown.Checked, this.cbMatchCase.Checked) == false)
{
MessageBox.Show("Cant find selected text");
}
else this.Close();
And I know what I have to do but I don't know to code it .. any help would be appreciated! ty
Upvotes: 2
Views: 2648
Reputation: 35
private void b1_Click(object sender, EventArgs e) {
string[] a = new string[100];`
string word = tb.Text;
WinFormsApp2.Form1 fi = new WinFormsApp2.Form1();
for (int i = 0; i < 100; i++)
{
if (word == fi.find[i])
{
MessageBox.Show("FOUNDED");
}
}
Upvotes: 0
Reputation: 13378
To start, try something like this, in the btnFind_Click event:
private btnFind_Click(Object sender, EventArgs e)
{
if(CountStringOccurrences(txtNotePad.Text, txtToFind.Text) > 0)
{
MessageBox.Show("Found 1 or multiple matches");
}
else
{
MessageBox.Show("Didn't found match...");
}
}
//CountStringOccurrences, takes full text + string to match with
//Returns the amount of matches found in full text
public static int CountStringOccurrences(string text, string pattern)
{
// Loop through all instances of the string 'text'.
int count = 0;
int i = 0;
while ((i = text.IndexOf(pattern, i)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
Upvotes: 0
Reputation: 564691
You'd typically use String.IndexOf to find the position of the match within the text box. This will let you use the TextBox.SelectionStart and SelectionLength
to set the selection.
public bool FindAndSelect(string TextToFind, bool MatchCase)
{
var mode = MatchCase ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
int position = textBox.Text.IndexOf(TextToFind, mode);
if (position == -1)
return false;
textBox.SelectionStart = position;
textBox.SelectionLength = TextToFind.Length;
return true;
}
Note the above doesn't handle "up/down" - to do that, you'd need to compare against the current SelectionStart
position, and see if there's a match after that. There is an overload of IndexOf which allows you to specify a starting point, which would make that easier to handle.
Upvotes: 1