|
Practical
Learning: Introducing File Information
|
|
- To start a new application, on the main menu, click File -> New
-> Project
- In the Templates list, click Windows Forms Application
- Set the name to WattsALoan1
- In the Properties window, change the form's Text to Watts
A Loan
- To be able to use the Visual Basic library, in the Solution
Explorer, right-click WattsALoan1 and click References...
- Click Add New Reference...
- In the .NET property page, click Microsoft.VisualBasic
- Click OK and OK
- In the Common Controls section of the Toolbox, click ToolTip and
click the form
- Design the form as follows:
 |
| Control |
Name |
Text |
ToolTip on toolTip1 |
| Label |
|
Acnt #: |
|
| Label |
|
Customer Name: |
|
| Label |
|
Customer: |
|
| TextBox |
txtAccountNumber |
|
Account number of the customer requesting
the loan |
| TextBox |
txtCustomerName |
|
Name of the customer requesting the loan |
| Label |
|
Empl #: |
|
| Label |
|
Employee Name: |
|
| Label |
|
Prepared By: |
|
| TextBox |
txtEmployeeNumber |
|
Employee number of the clerk preparing the
loan |
| TextBox |
txtEmployeeName |
|
Name of the clerk preparing the loan |
| Button |
btnNewEmployee |
|
Used to add a new employee to the company |
| Label |
|
Loan Amount: |
|
| TextBox |
txtLoanAmount |
|
Amount of loan the customer is requesting |
| Label |
|
Interest Rate: |
|
| TextBox |
txtInterestRate |
|
Annual percentage rate of the loan |
| Label |
|
% |
|
| Label |
|
Periods |
|
| TextBox |
|
txtPeriods |
The number of months the loan is supposed
to last |
| Button |
btnCalculate |
Calculate |
Used to calculate the monthly payment |
| Label |
|
Monthly Payment: |
|
| TextBox |
txtMonthlyPayment |
|
The minimum amount the customer should pay
every month |
| Button |
btnClose |
Close |
Used to close the form |
|
- Double-click the Calculate button and implement its event as
follows:
System::Void btnCalculate_Click(System::Object^ sender,
System::EventArgs^ e)
{
double LoanAmount, InterestRate, Periods, MonthlyPayment;
try {
LoanAmount = double::Parse(txtLoanAmount->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid Loan Amount");
}
try {
InterestRate = double::Parse(txtInterestRate->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid Interest Rate");
}
try {
Periods = double::Parse(txtPeriods->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid Periods Value");
}
try {
MonthlyPayment =
Microsoft::VisualBasic::Financial::Pmt(
InterestRate / 12 / 100,
Periods,
-LoanAmount,
0 ,
Microsoft::VisualBasic::DueDate::BegOfPeriod);
txtMonthlyPayment->Text = MonthlyPayment.ToString(L"C");
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid Periods Value");
}
}
|
- Return to the form and double-click the Close button to implement
its event as follows:
System::Void btnClose_Click(System::Object^ sender, System::EventArgs^ e)
{
Close();
}
|
- Return to the form
The FileInfo class is equipped with one constructor
whose syntax is:
public:
FileInfo(String ^ fileName);
This constructor takes as argument the name of a file or its
complete path. If you provide only the name of the file, the compiler would consider
the same directory of its project. Here is an example:
FileInfo ^ fleMembers = gcnew FileInfo(L"First.txt");
Alternatively, if you want, you can provide any valid
directory you have access to. In this case, you should provide the complete
path.
|
Practical
Learning: Initializing a File
|
|
- Double-click an unoccupied area on the body form
- Scroll up completely and, under the other using lines, type using
namespace System::IO
- Scroll down complement and change the Load event of the form as follows:
System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
}
|
- Save the file
The FileInfo constructor is mostly meant only to
indicate that you want to use a file, whether it exists already or it would be
created. Based on this, if you execute an application that has only a FileInfo
object created using the constructor as done above, nothing would happen.
To create a file, you have various alternatives. If you want
to create one without writing anything in it, which implies creating an empty file,
you can call the FileInfo::Create() method. Its syntax is:
public:
FileStream ^ Create();
This method simply creates an empty file. Here is an example
of calling it:
FileInfo ^ fleMembers = gcnew FileInfo(L"First.txt");
fleMembers->Create();
The FileInfo::Create() method returns a FileStream
object. You can use this returned value to write any type of value into the
file, including text. If you want to create a file that contains text, an
alternative is to call the FileInfo::CreateText() method. Its syntax is: public:
StreamWriter CreateText();
This method directly returns a StreamWriter
object. You can use this returned object to write text to the file.
When you call the FileInfo::Create() or the FileInfo::CreateText()
method, if the file passed as argument, or as the file in the path of the
argument, exists already, it would be deleted and a new one would be created with
the same name. This can cause the right file to be deleted. Therefore, before
creating a file, you may need to check whether it exists already. To do this,
you can check the value of the Boolean FileInfo::Exists property. This
property holds a true value if the file exists already and it holds a false
value if the file doesn't exist or it doesn't exist in the path.
Here is an example of checking the existence of a file:
FileInfo ^ fleMembers = gcnew FileInfo(L"First.txt");
fleMembers->Create();
if( fleMembers.Exists == true )
return;
|
Practical
Learning: Creating a Text File
|
|
- Change the Load event of the form as follows:
System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
// If the employees file was not created already,
// then create it
if( !fiEmployees->Exists )
{
StreamWriter ^ stwEmployees = fiEmployees->CreateText();
}
}
|
- Save the file
As mentioned earlier, the FileInfo::Create() method
returns a FileStream object. You can use this to specify the type of
operation that would be allowed on the file.
To write normal text to a file, you can first call the FileInfo::CreateText()
method. This method returns a StreamWriter object. The StreamWriter
class is based on the TextWriter class that is equipped with the Write()
and the WriteLine() methods used to write values to a file. The Write()
method writes text on a line and keeps the caret on the same line. The WriteLine()
method writes a line of text and moves the caret to the next line.
After writing to a file, you should close the StreamWriter
object to free the resources it was using during its operation(s).
|
Practical
Learning: Writing to a Text File
|
|
- Change the Load event of the form as follows:
System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
// If the employees file was not created already,
// then create it
if( !fiEmployees->Exists )
{
StreamWriter ^ stwEmployees = fiEmployees->CreateText();
// And create a John Doe employee
try {
stwEmployees->WriteLine(L"00-000");
stwEmployees->WriteLine(L"John Doe");
}
finally
{
stwEmployees->Close();
}
}
}
|
- Save the file
You may have created a text-based file and written to
it. If you open such a file and find out that a piece of information is
missing, you can add that information to the end of the file. To do this,
you can call the FileInfo::AppenText() method. Its syntax is:
public:
StreamWriter ^ AppendText();
When calling this method, you can retrieve the StreamWriter
object that it returns, then use that object to add new information to the
file.
|
Practical
Learning: Writing to a Text File
|
|
- To create a new form, on the main menu, click Project -> Add New
Item...
- In the Templates list, click Windows Form
- Set the Name to NewEmployee and click Add
- Design the form as follows:
 |
| Control |
Text |
Name |
| Label |
Employee #: |
|
| TextBox |
|
txtEmployeeNumber |
| Label |
Employee Name: |
|
| TextBox |
|
txtEmployeeName |
| Button |
Create |
btnCreate |
| Button |
Close |
btnClose |
|
- Right-click the form and click View Code
- In the top section of the file, under the using using lines, type
using namespace System::IO;
- Return to the New Employee form and double-click the Create button
- Implement its event as follows:
System::Void btnCreate_Click(System::Object^ sender, System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
StreamWriter ^ stwEmployees = nullptr;
// Normally, we should have the file already but just in case...
if( !fiEmployees->Exists )
stwEmployees = fiEmployees->CreateText();
else // If the file exists already, then we will only add to it
stwEmployees= fiEmployees->AppendText();
try {
stwEmployees->WriteLine(txtEmployeeNumber->Text);
stwEmployees->WriteLine(txtEmployeeName->Text);
}
finally
{
stwEmployees->Close();
}
txtEmployeeNumber->Text = L"";
txtEmployeeName->Text = L"";
txtEmployeeNumber->Focus();
}
|
- Return to the New Employee form and double-click the Close button
- Implement its event as follows:
System::Void btnClose_Click(System::Object^ sender, System::EventArgs^ e)
{
Close();
}
|
- Access the Form1 form
- Double-click the top New button
- In the top section of the file, under the #pragma once line, type
#include "NewEmployee.h"
- Scroll down and implement its Click event as follows:
System::Void btnNewEmployee_Click(System::Object^ sender,
System::EventArgs^ e)
{
NewEmployee ^ frmNewEmployee = gcnew NewEmployee;
frmNewEmployee->ShowDialog();
}
|
- Return to the form
- In the combo box on top of the Properties window, select txtEmployeeNumber
- On the Properties window, click the Events button and double-click Leave
- Implement the event as follows:
System::Void txtEmployeeNumber_Leave(System::Object^ sender,
System::EventArgs^ e)
{
String ^ strFilename = L"Employees.wal";
FileInfo ^ fiEmployees = gcnew FileInfo(strFilename);
if(fiEmployees->Exists )
{
if( txtEmployeeNumber->Text == L"" )
{
txtEmployeeName->Text = L"";
return;
}
else
{
StreamReader ^ strEmployees = fiEmployees->OpenText();
String ^ strEmployeeNumber, ^ strEmployeeName;
bool found = false;
try {
while( strEmployeeNumber = strEmployees->ReadLine() )
{
if( strEmployeeNumber == txtEmployeeNumber->Text )
{
strEmployeeName = strEmployees->ReadLine();
txtEmployeeName->Text = strEmployeeName;
found = true;
}
}
// When the application has finished checking the file
// if there was no employee with that number, let the user know
if( found == false )
{
MessageBox::Show(L"No employee with that number was found");
txtEmployeeName->Text = L"";
txtEmployeeNumber->Focus();
}
}
finally
{
strEmployees->Close();
}
}
}
}
|
- Execute the application to test it
- First create a few employees as follows:
| Employee # |
Employee Name |
| 42-806 |
Patricia Katts |
| 75-148 |
Helene Mukoko |
| 36-222 |
Frank Leandro |
| 42-808 |
Gertrude Monay |
- Process a loan

- Close the application
|
|