Pages

Implementing the Find Function in Sample Notepad using C#

For Previous tutorial
http://futurextech.blogspot.com/2013/12/creating-sample-notepad-application.html

Find
Create another web form which will pop on clicking find Menuitem.





namespace Notepad_X
{
    public partial class Find : Form
    { 
        public Find()
        {
            InitializeComponent();
        }
//cancel button
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
//find next button
        private void button1_Click(object sender, EventArgs e)
        {
            Functions.TextToFind = textBox1.Text;
            
            this.Close();
        }

        private void Find_Load(object sender, EventArgs e)
        {
            if (Functions.TextToFind != null)
                textBox1.Text = Functions.TextToFind;
        }

    }
 }
---------------------------------------------------------------------------------------------

Now Add > New Item >Code file
Name this file as Functions.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Notepad_X
{
    static  class Functions
    {
        public static string TextToFind { get; set; }

    }
}


Now Add the following method in main form (In our example Form1.cs)


private void Find(string textToFind, ref Find findForm)
        {
            //If there isn't found the text specified
            if (txtcontent.Text.IndexOf(textToFind) == -1)
            {
                //Show a message to the user
                MessageBox.Show("Cannot find '" + textToFind + " '");
                //And show the dialog again
                findForm.ShowDialog();
            }
            else
            {
                //If it is found
                //Put the cursor at the start of it
                txtcontent.SelectionStart = txtcontent.Text.IndexOf(Functions.TextToFind);
                //And select it
                txtcontent.SelectionLength = textToFind.Length;
            }
        }

-----------------------------------------------------------------
For Clicking Find Menu Item In main form (Form1.cs)

private void findCtrlFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Find findForm = new Find();
            //Show the find dialog
            findForm.ShowDialog();
            Find(Functions.TextToFind, ref findForm);
           

        }

No comments:

Post a Comment