Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать

490 Project 3 ADO.NET IN MANAGED C++

emailid->Location = Drawing::Point(width/2-120, height - 240); Controls->Add(emailid);

heading = new Label();

heading->Text=”Referral A/C no:”; heading->Size = Drawing::Size(100, 20);

heading->Location = Drawing::Point(width/2-240, height - 220);

Controls->Add(heading);

 

Y

 

 

 

L

refacno = new TextBox();

F

refacno->Name=”refacno”;

 

 

M

 

refacno->Size = Drawing::Size(150, 40); refacno->TabIndex = 2;

refacno->LocationA= Drawing::Point(width/2-120, height - 220); Controls->Add(refacno);E

heading T= new Label(); heading-> ext=”Amount:”;

heading->Size = Drawing::Size(50, 40);

heading->Location = Drawing::Point(width/2+40, height - 360); Controls->Add(heading);

amount = new TextBox(); amount->Name=”amt”;

amount->Size = Drawing::Size(80, 40); amount->TabIndex = 2;

amount->Location = Drawing::Point(width/2+100, height - 360); Controls->Add(amount);

//These are some of the hidden fields to store the values

//that are required in the table but are not modified by

//the user

va = new TextBox(); va->Name=”validacc”; va->Text=”VA”; va->Visible = false; Controls->Add(va);

Team-Fly®

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 491

typeac = new TextBox(); typeac->Name=”typeofacc”; typeac->Text=”S”; typeac->Visible = false; Controls->Add(typeac);

// application heading heading = new Label();

heading->Text=”SaveMyMoneyBank Application”; heading->Size = Drawing::Size(180, 50);

heading->Location = Drawing::Point(width/2-80, height - 380); Controls->Add(heading);

// Set up Clear fields button clearfields = new Button(); clearfields->Text = “Clear Fields”;

clearfields->Size = Drawing::Size(100, 30); clearfields->TabIndex = 0;

clearfields->Location = Drawing::Point(width/2+80, height - 320); clearfields->Click += (new EventHandler(this, &BankForm::OnClearFields)); Controls->Add(clearfields);

// Set up Insert record button insertrecord = new Button(); insertrecord->Text = “Insert New Record”;

insertrecord->Size = Drawing::Size(100, 30); insertrecord->TabIndex = 0;

insertrecord->Location = Drawing::Point(width/2+80, height - 280); insertrecord->Click += (new EventHandler(this,

&BankForm::OnInsertRecord)); Controls->Add(insertrecord);

// Set up the Update record button updaterecord = new Button(); updaterecord->Text = “Update Current Record”; updaterecord->Size = Drawing::Size(100, 30); updaterecord->TabIndex = 0;

updaterecord->Location = Drawing::Point(width/2+80, height - 240);

492 Project 3 ADO.NET IN MANAGED C++

updaterecord->Click += (new EventHandler(this,

&BankForm::OnUpdateRecord));

Controls->Add(updaterecord);

}

After the call to CreateControls, the constructor of the BankForm class calls the method FetchData. The FetchData method retrieves the data from the database and calls the FillFields method, which updates the controls with the data from the dataset, retrieved by FetchData. The FetchData method is called whenever current data is to be retrieved from the database.

Here is the complete listing for the FetchData method:

void FetchData()

{

// user id and password

String *userId = “sa”;

String *password = “”;

// Connect to the SQL Database and issue a SELECT command all in one statement

String *query = S”SELECT * FROM Account_Detail”;

// build connect string with the userid and password

String *connectString = String::Format(S”Data Source=localhost;Database=Banking;UID={0};Password={1};”, userId, password);

// Create the connection object

SqlConnection* sqlconn = new SqlConnection(connectString); sqlconn->Open();

// set the adapter with the main command myAdapter = new SqlDataAdapter(query,sqlconn);

// set the various commands to be operated on the database

SqlCommandBuilder* DataAdapterCommands = new

SqlCommandBuilder(myAdapter);

// Create the Dataset ds = new DataSet();

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 493

//Fill the dataset using the fill method of the adapter

//also include the table that is used to populate it

myAdapter->Fill(ds, “Account_Detail”);

//call the functions to fill the fields with the records

//passing 0 is for the first row

FillFields(currentrec);

// Close the connection sqlconn->Close();

}

Next, you will look at the FillFields method that is called by the FetchData method to update the controls with the data from the database. The method takes a row number as a parameter and fills the controls on the form with the data from that row in the dataset.

void FillFields(int i)

{

DataTable *dtab = new DataTable();

DataRow *dr;

// set an alias for the data table collections dtab = ds->get_Tables()->get_Item(0);

//set an alias for the data row collections based on the value of i dr = dtab->get_Rows()->get_Item(i);

if(dr != NULL)

{

// fill each field on the form with the current dataset row fname->set_Text(dr->get_Item(“First_name”)->ToString());

lname->set_Text(dr->get_Item(“Last_name”)->ToString()); dob->set_Text(dr->get_Item(“date_birth”)->ToString()); paddr->set_Text(dr->get_Item(“Permanent_Addr”)->ToString()); maddr->set_Text(dr->get_Item(“Mailing_Addr”)->ToString()); phno->set_Text(dr->get_Item(“Phone_Number”)->ToString()); emailid->set_Text(dr->get_Item(“eMailID”)->ToString());

494 Project 3 ADO.NET IN MANAGED C++

refacno->set_Text(dr->get_Item(“Ref_Acc_no”)->ToString());

amount->set_Text(dr->get_Item(“Balance”)->ToString());

}

}

The form has buttons and menu options that allow navigation between records. There are options for moving to the first record, the previous record, the next record, and the last record. The following event handler methods provide the functionality. A variable currentrec is used to maintain the current record number.

The OnFirstRecord method simply calls the FillFields method with a parameter 0:

void OnFirstRecord(Object *sender, EventArgs *e)

{

//call the functions to fill the fields with the records

//passing 0 is for the first row

FillFields(0); currentrec = 0;

}

void OnPrevRecord(Object *sender, EventArgs *e)

{

//call the functions to fill the fields with the records

//pass current record -> ‘1’ is for the previous row

if(currentrec != 0)

{

FillFields(currentrec-1); currentrec = currentrec-1;

}

}

void OnNextRecord(Object *sender, EventArgs *e)

{

// call the functions to fill the fields with the records //The count of records is retrieved

lastrow = (ds->get_Tables()->get_Item(0)->get_Rows()->get_Count() - 1);

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 495

//a check is made to see if the current record is the last one if(currentrec != lastrow)

{

FillFields(currentrec+1); currentrec = currentrec+1;

}

}

void OnLastRecord(Object *sender, EventArgs *e)

{

//call the functions to fill the fields with the records

//passing ‘lastrow-1’ for the last row

lastrow = (ds->get_Tables()->get_Item(0)->get_Rows()->get_Count() - 1); FillFields(lastrow);

currentrec = lastrow;

}

The BankForm class also has buttons for inserting a new record and for updating an existing record. The OnInsertRecord and OnUpdateRecord methods handle the events of these buttons.

The OnInsertRecord method calls the ValidateForm method to ensure that none of the required fields is blank. If ValidateForm returns false, it sets the text of the button to “submit” and returns. Otherwise, the method does the following:

1.Creates a new DataRow object.

2.Sets the fields of the DataRow object with data from the form controls.

3.Adds the DataRow object to the DataSet.

Following is a listing of the OnInsertRecord method:

void OnInsertRecord(Object *sender, EventArgs *e)

{

if (flag==false)

{

ClearForm();

flag=true;

insertrecord->Text=”Submit”;

return;

496 Project 3 ADO.NET IN MANAGED C++

}

if (ValidateForm()==true)

{

flag=false;

insertrecord->Text=”Insert New Record”; DataRow *dr;

// create a new datarow object

dr = ds->get_Tables()->get_Item(0)->NewRow();

// fill each Datarow field with the values on the form

dr->set_Item(“First_name”, fname->Text->ToString()); dr->set_Item(“Last_name”,lname->Text->ToString()); dr->set_Item(“date_birth”,dob->Text->ToString()); dr->set_Item(“Permanent_Addr”,paddr->Text->ToString()); dr->set_Item(“Mailing_Addr”,maddr->Text->ToString()); dr->set_Item(“Phone_Number”,phno->Text->ToString()); dr->set_Item(“eMailID”,emailid->Text->ToString()); dr->set_Item(“Ref_Acc_no”,refacno->Text); dr->set_Item(“Balance”,amount->Text);

//random account number generation

//this can be replaced by some logic

dr->set_Item(“Account_number”,amount->Text);

// default values picked up for update requirements dr->set_Item(“Type_account”,typeac->Text); dr->set_Item(“Valid_acc”,va->Text);

// add the row to the data set ds->get_Tables()->get_Item(0)->get_Rows()->Add(dr);

//use the update method of the adapter to update the

//database from the contents of the dataset.

//this can also be called later at any point

myAdapter->Update(ds,”Account_Detail”);

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 497

// the following function is to refresh the form with the latest data

FetchData();

MessageBox::Show(“Record added successfully.”);

}

}

The OnUpdateRecord method updates the current record that is being displayed on the form, into the database, whenever clicked on:

void OnUpdateRecord(Object *sender, EventArgs *e)

{

//when the current record is displayed

//the user changes any field and clicks on the update button

//this function will ensure that it is updated in the database

if (ValidateForm()==true)

{

DataTable *dtab = new DataTable();

DataRow *dr;

// set an alias for the data table collections dtab = ds->get_Tables()->get_Item(0);

//set an alias for the data row collections for the current row dr = dtab->get_Rows()->get_Item(currentrec);

// fill each Datarow members with the latest values dr->set_Item(“First_name”, fname->Text->ToString()); dr->set_Item(“Last_name”,lname->Text->ToString()); dr->set_Item(“date_birth”,dob->Text->ToString()); dr->set_Item(“Permanent_Addr”,paddr->Text->ToString()); dr->set_Item(“Mailing_Addr”,maddr->Text->ToString()); dr->set_Item(“Phone_Number”,phno->Text->ToString()); dr->set_Item(“eMailID”,emailid->Text->ToString()); dr->set_Item(“Ref_Acc_no”,refacno->Text); dr->set_Item(“Balance”,amount->Text);

// random account number generation dr->set_Item(“Account_number”,amount->Text);

498 Project 3 ADO.NET IN MANAGED C++

// default values picked up for update requirements dr->set_Item(“Type_account”,typeac->Text); dr->set_Item(“Valid_acc”,va->Text);

//use the update method of the adapter to update the

//database from the contents of the dataset.

//this can also be called later at any point

myAdapter->Update(ds,”Account_Detail”);

// the following function is to refresh the form with the latest data

FetchData();

MessageBox::Show(“Record updated successfully.”);

}

}

The class also uses a couple of support methods, ClearForm and ValidateForm, to clear all the controls and to validate the contents of the controls before an insert or update operation. The ClearForm method simply sets the Text property of all the text boxes to a blank string:

void ClearForm()

{

fname->set_Text(“”);

lname->set_Text(“”);

dob->set_Text(“”);

paddr->set_Text(“”);

maddr->set_Text(“”);

phno->set_Text(“”);

emailid->set_Text(“”);

refacno->set_Text(“”);

amount->set_Text(“”);

}

The ValidateForm method checks to see if any of the required fields on the form are left blank before a insert or update operation, and calls the SetError method of an ErrorProvider object with the name of the control causing the error and the error message. The ErrorProvider object has been declared in the BankForm class and initialized in the constructor. The ErrorProvider class provides a user inter-

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 499

face element that can be used to show a flashing error icon next to a control, to indicate that the control has an error associated with it. This has been initialized in the constructor of the BlankForm class, as shown here:

error=new ErrorProvider();

error->BlinkRate=250;

error->BlinkStyle=ErrorBlinkStyle::BlinkIfDifferentError;

The blink rate is the time in milliseconds between each blink of the icon. The BlinkStyle property can have the following enumerated values:

ErrorBlinkStyle::AlwaysBlink. Starts blinking when the error icon is first displayed or, if the icon is already displayed, when its error text is set

ErrorBlinkStyle::BlinkIfDifferentError. Starts blinking when the error text changes

ErrorBlinkStyle::NeverBlink. Never blinks

Now for the code of the ValidateForm method:

bool ValidateForm()

{

if (fname->Text->get_Length()==0)

{

error->SetError(fname,”Invalid name”); return false;

}

else

error->SetError(fname,””); if (lname->Text->get_Length()==0)

{

error->SetError(lname,”Invalid name”); return false;

}

else

error->SetError(lname,””); if (dob->Text->get_Length()==0)

{

error->SetError(dob,”Invalid date of birth”); return false;

}