Text Editor in Visual Basic
Submitted by Yorkiebar on Tuesday, May 27, 2014 - 03:43.
Introduction:
This tutorial is on how to create a basic text editor in Visual Basic.
Design:
The design for this program is;
Button, button1, Save the document.
Button, button2, Open a document.
Textbox, textbox1, Contain the document text.
Imports:
The only thing we need to import is System.IO which allows us to access files from the computers FileSystem...
Button1 Click:
To save a document, we first want to ensure that the textbox1 text is not empty (so there is something to actually save)...
Then if there is something to save, we are going to create a msgbox prompt asking if they want to specify a new save location. If the answer is no, the document will be saved to the path of a variable named 'path' which we are yet to create.
Variables:
The path variable I talked about earlier will simply hold the latest opened documents path so that we can offer the overwrite functionality later on. We create this in the global scope (outside of any other subs, functions or classes)...
Button2 Click:
To open a document, we simply give the user a new OpenFileDialog, allow them to select a file, and then read it to the textbox (textbox1)...
- Imports System.IO
- If (Not TextBox1.Text = Nothing) Then
- Else
- MsgBox("Nothing to save!")
- End If
- If (Not path = Nothing) Then
- Dim result = MsgBox("Would you like to save to a new location? (No = Save overwrite)", MsgBoxStyle.YesNoCancel, "Save Location")
- If (result = MsgBoxResult.Yes) Then
- Using fs As New SaveFileDialog
- fs.MultiSelect = False
- fs.RestoreDirectory = False
- fs.ShowDialog()
- If (Not fs.FileName = Nothing) Then
- Using sw As New StreamWriter(fs.FileName)
- sw.Write(TextBox1.Text)
- End Using
- End If
- End Using
- Else If (result = MsgBoxResult.No) Then
- Using sw As New StreamWriter(path)
- sw.Write(TextBox1.Text)
- End Using
- End If
- Else
- Using fs As New SaveFileDialog
- fs.MultiSelect = False
- fs.RestoreDirectory = False
- fs.ShowDialog()
- If (Not fs.FileName = Nothing) Then
- Using sw As New StreamWriter(fs.FileName)
- sw.Write(TextBox1.Text)
- End Using
- End If
- End Using
- End If
- Dim path As String = ""
- Using fo As New OpenFileDialog
- fo.MultiSelect = False
- fo.RestoreDirectory = False
- fo.ShowDialog()
- If (Not fo.FileName = Nothing) Then
- Using sr As New StreamReader(fo.FileName)
- While (sr.Peek <> -1)
- Textbox1.Text += sr.ReadLine()
- End While
- End Using
- End If
- End Using
Add new comment
- 48 views