Lecture 3
Lecture 3
The OpenFileDialog control prompts the user to open a file and allows the user to select a
file to open. The user can check if the file exists and then open it.
The OpenFileDialog control class inherits from the abstract class FileDialog.
Following is the Open File dialog box −
Example
In this example, let's load an image file in a picture box, using the open file dialog box. Take
the following steps −
Drag and drop a PictureBox control, a Button control and a OpenFileDialog control on
the form.
Set the Text property of the button control to 'Load Image File'.
Double-click the Load Image File button and modify the code of the Click event:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub
When the application is compiled and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
Click on the Load Image File button to load an image stored in your computer.
The SaveFileDialog control prompts the user to select a location for saving a file and allows
the user to specify the name of the file to save data
Example
In this example, let's save the text entered into a rich text box by the user using the save file
dialog box. Take the following steps −
Drag and drop a Label control, a RichTextBox control, a Button control and a
SaveFileDialog control on the form.
Set the Text property of the label and the button control to 'We appreciate your
comments' and 'Save Comments', respectively.
Double-click the Save Comments button and modify the code of the Click event as
shown −
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog1.FileName, RichTextBox1.Text, True)
End If
End Sub
FontFileDialog Control prompts the user to choose a font from among those installed on the
local computer and lets the user select the font, font size, and color. It returns the Font and
Color objects
Example
In this example, let's change the font and color of the text from a rich text control using the
Font dialog box. Take the following steps −
Drag and drop a RichTextBox control, a Button control and a FontDialog control on
the form.
Set the Text property of the button control to 'Change Font'.
Set the ShowColor property of the FontDialog control to True.
Double-click the Change Color button and modify the code of the Click event −
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FontDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
RichTextBox1.ForeColor = FontDialog1.Color
RichTextBox1.Font = FontDialog1.Font
End If
End Sub