WiredWX Christian Hobby Weather Tools
Would you like to react to this message? Create an account in a few clicks or log in to continue.

WiredWX Christian Hobby Weather ToolsLog in

 


Simple Notepad Tutorial - C#

+7
mrichat
luisperezphd
CY5
SomeDude
mr_munchie
Immortal
Programmer
11 posters

descriptionSimple Notepad Tutorial - C# EmptySimple Notepad Tutorial - C#

more_horiz
In this tutorial we will be making a simple C# Notepad with the option to Clear, Cut, Copy, Paste, Select All, Save, Open, and exit. I am using Visual Studio 2008 to make this tutorial, but you can use any C# editor that you like, although, we will be making a GUI so you probably want to use either Visual Studio or Visual C# to follow.

All right, so now we can start making the GUI.

Step 1: Starting a new project.

To start a new project, goto File -> New Project -> Windows Form Application and name it whatever you want.
You should get a blank GUI named Form1, if you do goto Step 2, if not post a reply and tell me what your problem is, I am glad to help.

Step 2: Making the GUI

For this Notepad application we are going to be using a RichTextBox for the editor. So, goto your Toolbox and select richTextBox and put it onto your application form (Make sure to leave room at the top for the menu).

All right, now you have your editor area, but we need to make a menu for the people using your application to use some features, so add a MenuStrip and type in the first box "File". Then there will be a drop down box to add more stuff, add "New", then click the little down arrow on the next one and click Seperator, this will make a line seperating the different menu options. After the seperator add "Save File" and then "Open File", then a seperator, then "Exit".

All right, now you have your File menu, now next to File make another called "Edit", then for this one add "Cut", "Copy", and "Paste", and Select All to the Edit menu.

There, now your menu is finished, onto Step 3 where we finally start coding!

Step 3: Adding events to the menu

All right, so now we have our GUI, we can run it but the buttons don't do anything. That is because we have not programmed in the events for these buttons yet, now this might sound difficult to some of you, but Visual Studio and Visual C# make it very easy to do this, as it makes the event command for us, we just have to tell it what to do, so double click on the "New" menu item under the file menu and it should take you to some code, your code should look something like this,

Code:

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Notepad
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // This is where the code for the button click of "New" is going to go.
        }
    }
}


Ok, so now under the private void newToolStripMenuItem_Click we need to add this code,

Code:

richTextBox1.Clear();


This basically calls the richTextBox1 which is the name of the richTextBox in your form, and tells it to Clear. This code is really simple and most of the commands for the buttons will look sorta like this.

So now your code should look like so,

Code:

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Notepad
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }
    }
}


Now, run your project and type something in, then click the new menu button and see if it clears the text, if it does great, but if it doesn't don't get discouraged, just reply and I will be sure to tell you your problem.

Ok, now let's make the exit button code, I know we are skipping Open and Save, but they are the hardest to grasp, so we will do those last, in C# it doesn't matter in what order you code your buttons as long as there is a click command for them, they will work.

For the Exit button, it is extremly simple, it is just simply

Code:

Close();
so just double click the exit button and for the code just type in Close();

For the Cut, Copy, Paste, and Select All buttons, they are all pretty much the same as the new button, but with different command, but still referring back to the richTextBox.

So, I am going to list the code for each button, just double click the right button and add the right code for that button command, it can't get much easier than copy and paste.

Cut:

Code:

richTextBox1.Cut();


Copy:

Code:

richTextBox1.Copy();


Paste:

Code:

richTextBox1.Paste();


Select All:

Code:

richTextBox1.SelectAll();


Ok, so now just save and run your program and see if everything is working so far, if so, carry on, if not leave a reply and I will get back to you.

Ok, now for the hardest part, the Save and Open options, go back into your GUI form and add a openFileDialog, and saveFileDialog. It doesn't matter where you place them on the form, they will just be put at the bottom for easy placement.

Ok, now double click on the saveFileDialog, as we will do that first.

Now, the code for this is,

Code:

saveFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|All Files (*.*)|*.*";
            saveFileDialog1.Title = "Save File";
            saveFileDialog1.OverwritePrompt = true;

            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
            }


Now, this can look like alot of code for beginners, but if you look at it logically, it is really quite simple.

Code:

saveFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|All Files (*.*)|*.*";
this is the part most people have trouble grasping. Basically what we are doing is setting the Save As Type: in the save file dialog box. So, if you goto Notepad (the real one with Windows) then when you click Save, you get a little thing down at the bottom that says "Save as type:" and you can click which one you want, that is what we are setting here. We are saying that the user can save a file as a .txt Text Document, a .rtf Rich Text Document, or they can specify there own .whatever extension.

The "|" seperate the different things it can be, like "Text Document (.txt) is what shows up when the user is looking at it, but the *.txt is what the program is going to save it as, * as a wildcard for the name they choose, and .txt as the extension. Same for the rest of them.

[code[saveFileDialog1.Title = "Save File";
saveFileDialog1.OverwritePrompt = true;[/code]

This is setting the title of the Save File prompt to Save File and making the Save File prompt the user if he/she has to overwrite a file or not. If you do not put overwrite prompt as true, it is false by default and it will overwrite the file without asking the user. Not smart.

If you do not know what if statements are, they are basically a way to check to see if a certain condition is true, based on a given statement, so the code,

Code:

if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
            }


Is basically asking the user (I am going to put this into human words so you can understand it) if they click the OK button on the save file dialog box then save the file that they have typed up.

And that is it, if you wanted to you could add some error handling, but we will save that for another tutorial.

So, lets do the open dialog, which is almost the same as the save file dialog, but with minor differences. I will point them out in the code.

Code:

openFileDialog1.Title = "Open File";
            openFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|All Files (*.*)|*.*";
            // There is no overwrite prompt, because we don't need one if we are opening a file.

            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                richTextBox1.LoadFile(openFileDialog1.FileName);
                // This is a little different because we are just opening a file, not saving it, so there are not as many parameters.
            }


Let me go over just this little bit of code and we are finished with the tutorial,

Code:

richTextBox.LoadFile(openFileDialog.FileName);


This basically says, once again referring back to richTextbox1, Load the file name that the user has typed in or clicked on. Simple, yet effective.

All right, so that is it for this tutorial, just leave a reply if you want me to make more tutorials or if you have any problems.

Also, I am going to make another tutorial on how to do this exact same thing in VB.NET later so get ready for some more tutorials.

Thanks for reading (I am not just going to give you the source, because this is a tutorial and that wouldn't help you learn anything),
- Programmer

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
Ok, I'm sorry for finding this almost a month later, but I feel i should post this for the newbies that read this and go "What the f*** is wrong with it?!" lol.
The entire thing except for the open/save is good, (tested personally) here's your problem with the open/save options:
The

Code:

openFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|All Files (*.*)|*.*";

and

Code:


saveFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|All Files (*.*)|*.*";

Is invalid, due to when you put in the .rtf extension, you forgot to add |*.rtf|
at the end of the rtf type, and instead just continued to the All Files.
here's the proper code for both:
(save):

Code:


saveFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|*.rtf|All Files (*.*)|*.*";

(open):

Code:


openFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|*.rtf|All Files (*.*)|*.*";

PS:
I just found the error while debugging, and though people should know - I am trying not to pretend I'm pro at this, as for i just started Windows-Platform C# (I used to code java C#), and this helped me just as much as it helped anyone else. Big Grin
Thank You!

descriptionSimple Notepad Tutorial - C# EmptyI like it, but....

more_horiz
Hi, I'm very new to C# programming. I've been using Perl for sometime now but want to write some Window apps.

I found this tutorial very useful. I have some issues with it.

Please feel free to correct me. It's the only way I'm going to learn.

#1, I could not get the Open or Save dialog boxes to open. I think I followed your instructions.
On the line were to say "Ok, now double click on the saveFileDialog, as we will do that first.".
I assumed you wanted the code written in saveFileDialog1_FileOk. The code looked like this.

private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) {
http://saveFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|All Files (*.*)|*.*";
saveFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|*.rtf|All Files (*.*)|*.*";
saveFileDialog1.Title = "Save File";
saveFileDialog1.OverwritePrompt = true;

if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}


This seems to do nothing. All I could think is that there is no link between the "open file" on the menu and the
saveFileDialog1_FileOk. So, I put the code into openFileToolStripMenuItem_Click_1. The code now looks like this.

private void openFileToolStripMenuItem_Click_1(object sender, EventArgs e) {
//OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Geek Police Open File";
openFileDialog1.Filter = "Text Document (.txt)|*.txt|Rich Text Document (.rtf)|*.rtf|All Files (*.*)|*.*";
// There is no overwrite prompt, because we don't need one if we are opening a file.

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
richTextBox1.LoadFile(openFileDialog1.FileName);
// This is a little different because we are just opening a file, not saving it, so there are not as many parameters.
}
}


I did this for both the open and save menu items. This would now open the save and open dialog boxes.

#2, I did the open dialog box first. I could not open any files. I found the problem
to be related to txt files. I was always trying to open a txt file. It was not until I
saved a file using this program which, then I discovered I could open it. It was then that I realised that
the program only supports rich text files.

I would like to stress that I found this tutorial very useful. I especially liked how you explained were the code
should be inserted into. A lot of the other tutorials skip over this. This is very annoying when you don't know
were the code should be. I would love it if you made some more tutorials like this one. I need to learn to walk before I can run.

Thanks again.

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
I think the confusion for issue #1 comes from the fact that the OP's instructions tell you to double-click the saveFileDialog item on the design surface but that's not actually what he has done. Double-clicking saveFileDialog creates an event handler function for the FileOk event defined by the abstract FileDialog class. This event can only be fired if the openFileDialog has been opened. I believe his intent was to say, "double click on the saveToolStripMenuItem," or something to that effect. That way you get an event handler generated for the toolstrip item's click event and that's where you should implement the OP's code.

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
SomeDude wrote:
I think the confusion for issue #1 comes from the fact that the OP's instructions tell you to double-click the saveFileDialog item on the design surface but that's not actually what he has done. Double-clicking saveFileDialog creates an event handler function for the FileOk event defined by the abstract FileDialog class. This event can only be fired if the openFileDialog has been opened. I believe his intent was to say, "double click on the saveToolStripMenuItem," or something to that effect. That way you get an event handler generated for the toolstrip item's click event and that's where you should implement the OP's code.

Yes SomeDude is right

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
But still there is problem While opening a different text file.
It show s error that invalid file format Let me think

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
Thanks for posting the code Programmer. It was helpful. I posted the code for my attempt at an exact notepad clone at http://www.simplygoodcode.com/2012/04/notepad-clone-in-net-winforms.html - maybe this will be helpful to someone else. If anyone finds anything wrong with it please let me know.

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
but where is the option to change the file name from "form1" to "saved name" after saving?
when debugging,the 'programmers notepad' runs with thye name"form1 or whatever he assigned the name of the form" but after saving with a particular name it supposed to show the file name whatever the saved name so.

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
I haven't explored the where in @Programmers code that happens. But in the notepad clone I posted this is the code:

Code:


        private bool SaveAs() {
            var SaveDialog = new SaveOpenDialog();
            SaveDialog.FileDlgFileName = Filename;
            SaveDialog.FileDlgDefaultExt = ".txt";
            SaveDialog.FileDlgFilter = "Text Documents (*.txt)|*.txt|All Files (*.*)|*.*";
            SaveDialog.Encoding = _encoding;
            SaveDialog.FileDlgCaption = "Save";
            SaveDialog.FileDlgOkCaption = "Save";
            
            if (SaveDialog.ShowDialog(this) != DialogResult.OK) return false;

            var PotentialFilename = SaveDialog.MSDialog.FileName;

            _encoding = SaveDialog.Encoding;
            File.WriteAllText(PotentialFilename, Content, _encoding);

            Filename = PotentialFilename;
            IsDirty = false;

            return true;
        }

       ...

        private string _Filename;
        public string Filename {
            get {
                return _Filename;
            }
            set {
                var oldvalue = value;
                _Filename = value;
                OnFilenameChanged(oldvalue, value);
            }
        }

        private void OnFilenameChanged(string oldvalue, string value) {
            OnDocumentNameChanged();
        }

        private void OnDocumentNameChanged() {
            UpdateTitle();
        }


Note the part where in the method call SaveAs() the property Filename gets assigned the value of PotentialFilename. The property upon changing triggers some events and method calls eventually lead to the title on form being updated.

Once again the full source is here: http://www.simplygoodcode.com/2012/04/notepad-clone-in-net-winforms.html

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
Hey! I'm a developer of an OS based off of open-source KDE code, and I'm making some pre-installed software for it using Visual C# such as a browser, a notepad, and a command line (though GRUB is already installed). Your tutorial is amazingly helpful to me!
WriteIn("hahaha I love C#!")  Big Grin 
 Thank You! 

............................................................................................

Volt the Villain

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
Do you guys have any more tuts you can post? This is very insightful, as I'm kinda learning it, and I heard we have a new developer on the site here... please Please (puppy eyes)

............................................................................................

Simple Notepad Tutorial - C# 2v1art10

"I can handle pain till it hurts"

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
Uhh still waiting on the tuts, guys! Thank You!

............................................................................................

Simple Notepad Tutorial - C# 2v1art10

"I can handle pain till it hurts"

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
Great post for newbies Thanks

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
nice thanks for share i wasn't aware about it

descriptionSimple Notepad Tutorial - C# EmptyRe: Simple Notepad Tutorial - C#

more_horiz
privacy_tip Permissions in this forum:
You cannot reply to topics in this forum