Basic Notepad in Visual Basic .NET
Submitted by Yorkiebar on Monday, August 4, 2014 - 07:35.
Introduction:
This tutorial is on how to make a simple Notepad text editor in Visual Basic .NET.
Controls:
The controls we will need are;
Button, button1, Save File
Button, button2, Open File
Textbox, textbox1, File Contents
Imports:
Before we begin, you need to import System.IO to allow our program to read and write to/from files. Put this at the top of your document...
Open File:
For the open file button, we are first going to create a temporary (using) OpenFileDialog box, and give it some basic properties...
We then show the dialog which allows the user to select a file to open. The 'ShowDialog()' function is a call blocking function so the code will pause while the user is selecting a file.
Once the file is selected, we first ensure that the user didn't click 'Close' by checking for a null/empty/nothing filename...
If it is a valid file, we read the contents to our textbox, 'textbox1'...
Save File:
To save our file, we use a similar procedure to our open file script. Except we use a SaveFileDialog box instead of an OpenFileDialog box.
Filters:
We could also limit our user to only saving .txt files by adding filters to our Open/Save FileDialog boxes, like so...
(Replace 'fo' with 'fs' for the saving script. Above is the open script.)
Finished!
Here is the full source code...
- Imports System.IO
- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
- Using fo As New OpenFileDialog
- fo.Multiselect = False
- fo.RestoreDirectory = True
- fo.ShowDialog()
- End Using
- End Sub
- If (Not fo.FileName = Nothing) Then
- End If
- TextBox1.Text = File.ReadAllText(fo.FileName)
- Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
- Using fs As New SaveFileDialog
- fs.RestoreDirectory = True
- fs.Filter = "Text Files|*.txt"
- fs.FilterIndex = 1
- fs.ShowDialog()
- If Not (fs.FileName = Nothing) Then File.WriteAllText(fs.FileName, TextBox1.Text)
- End Using
- End Sub
- fo.Filter = "Text Files|*.txt"
- fo.FilterIndex = 1
- Imports System.IO
- Public Class Form1
- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
- Using fo As New OpenFileDialog
- fo.Multiselect = False
- fo.RestoreDirectory = True
- fo.Filter = "Text Files|*.txt"
- fo.FilterIndex = 1
- fo.ShowDialog()
- If (Not fo.FileName = Nothing) Then
- TextBox1.Text = File.ReadAllText(fo.FileName)
- End If
- End Using
- End Sub
- Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
- Using fs As New SaveFileDialog
- fs.RestoreDirectory = True
- fs.Filter = "Text Files|*.txt"
- fs.FilterIndex = 1
- fs.ShowDialog()
- If Not (fs.FileName = Nothing) Then File.WriteAllText(fs.FileName, TextBox1.Text)
- End Using
- End Sub
- End Class
Comments
Add new comment
- Add new comment
- 2105 views