Visual C++.NET 2010 and 2008

by Jim Krumm

|Home| |Computer Science| |Casper College| |Java Source Code| |C++ Source Code| |Visual C++.NET| |Visual Basic| |Assembly Source Code| |Linux| |Dice Program|

|Wyoming| |Casper Area| |American Album| |Personal Album| |Hawaii| |Florida| |Denmark| |Greece| |Paris| |London| |Amsterdam| |Cozumel| |Links| |Sitemap|

Click here to go to the Computer Science Department Home Page for Casper College at www.caspercomsci.com. 


Below are some windows based applications written in C++ in our MFC class (COSC2405).  Conversion from Studio.NET 2003 to NET 2005 to NET 2008 to .NET 2010 and back can be challenging. The latest version of 2010.NET intellisense is missing in both the Express and Professional Editions, making it difficult to determine methods and parameters. This disadvantage is easily overcome by using an older version of Visual C++.NET 2008 which does support intellisense. The code is virtually identical in the 2008 and 2010 environment, making it easy to import or convert projects to the Visual Studio 2010 environment. Though automatic importation is usually possible, Visual C++ 2010.NET does not allow the importation of projects previously made in the 2008 environment employing Visual C++ DataSets in Database projects. One 2008 Visual C++ project is included below linking to a 2007 Access database using canned Visual C++ dataSets (precisely that type that will not import into the 2010 environment). A second database project is included below which links to an Access database directly without using dataSet objects in the Visual C++.NET 2010 and 2008 environment employing SQL commands.

Here a series of programs and tutorials that show how to write windows applications in C++ in the Studio.NET 2010 and 2008 environment.

Tutorial 1: Simple Intro on Setting up a Project and Using Basic Controls in Visual C++.NET 2010, 2008

Tutorial 2: Windows Basic Form Controls in C++ and Their Properties in Visual C++.NET 2010, 2008

Tutorial 3: Windows Forms and Useful ListBox Properties in Visual C++.NET 2010, 2008

Tutorial 4: Simple Animation, Which Shows the Use of the Timer and Location Commands using Visual C++.NET 2010, 2008

Tutorial 5: Menus using Visual C++.NET 2010, 2008

Tutorial 6: File Saving, Opening and Using Common Dialog Boxes using Visual C++.NET 2010, 2008

Tutorial 7: Concatenating Strings Together in the Windows C++ Environment using Visual C++.NET 2010, 2008

Tutorial 8: Detecting Asynchronous Keys using Visual C++.NET 2010, 2008

Tutorial 9: Using Arrays of Strings using Visual C++.NET 2010

Tutorial 10: Using SQL to Search and Modify an Access Database in Visual C++.NET 2010, 2008

Tutorial 11: Visual AddressBook using XML, Visual C++.NET 2008 and Access 2007

Tutorial 12: SQL Calls to a MySQL Database in Visual C++.NET 2010, 2008

Tutorial 13: Creating a Visual C++ Project from Scratch in 2010 that Calls an Access Database in Visual C++.NET 2010 (No XML or odbcad32)

Tutorial 14: Making A Setup or Deployment Package of a Microsoft Windows  Program in C++


Tutorial 1 : Simple Intro on Setting up a Project and Using Basic Controls in Visual C++.NET 2010, 2008

        This project will create a simple VB like interface using Windows C++ application in Microsoft Studio.NET 2008 which  transfers text from a TextBox to a Label at the click of a button.  Click here for the source code to the Click Me Program in Visual C++.NET for the 2010 version or here for the 2008 version. First set up the project by going to:

       File > New > Project  > Visual C++ Projects  > Windows Forms Application

       Then click browse and navigate to the folder to where you want to put your application and then click OK.  Name your project something simple like myInterface.  Go to the toolbox and add a button, a textbox and a label to your form, and make your form look something like this: 

Basic Controls in a Visual C++ Application

        To Change the caption on the button click on the button, and go to the buttons Property Window and select caption and type “Press Me”.   Click on the label, go to autosize under properties and set autosize to false. Still with the the label selected, set the borderstyle property to fixed3D. Go to text property for for the label remove all the text. Next double click on the button which will bring up the code window.     Add the one line of code between the brace below to the buton1_Click function:  

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)

       {

         label1->Text=textBox1->Text;

       }

        Notice the code you add is almost identical to what would be added in Studio.NET Visual Basic, except an arrow is used instead of  a period and the usual C++ semicolon and braces.

(Back) 


Tutorial 2: Windows Basic Form Controls in C++ and Their Properties Using Visual C++.NET 2010, 2008

        This program will show how to transfer an image to a pictureBox and do conversions from Strings to numerical values and numbers to String. Click here for the source code to the Basic Tools and Conversions Program in Visual C++.NET for the 2010 version or here to download the 2008 version. Set up a form that looks like this:    

Basic Controls in a Microsoft Visual C++ Program

        Set picturebox1 to a sizemode of stretchImage. Then within your project add a file called "heads.jpg" having a picture of a penny to your folder containing your .cpp source file and then add the following lines of code to the appropriate buttons functions:

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)

       {

         textBox1->Text="hi";

       }

private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)

     {

       label1->Text=textBox1->Text;

     }

private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e)

     {

       pictureBox1->Image=Image::FromFile("heads.jpg");

     }

private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e)

     {

       int num1;

       int num2;

       int answer;

       String ^strNum1;

       String ^strNum2;

       String ^strAnswer;

       strNum1=textBox2->Text;

       strNum2=textBox3->Text;

       num1=Int32::Parse(strNum1);

       num2=Int32::Parse(strNum2);

       answer=num1+num2;

       strAnswer=answer.ToString();

       label4->Text=strAnswer;

     }

 

(Back) 


Tutorial 3 : Windows Forms and Useful ListBox Properties Using Visual C++.NET 2010, 2008    

      This program will show how to use listboxes, and some of their more useful properties. Click here for the source code to the ListBox Demo Program in Visual C++.NET for the 2010 version or click here to download the 2008 version. First create a form which looks as follows, including the one listBox shown:

Listboxes in a Visual Microsoft C++ Program

      Code the buttons as followings:

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)

       {

         listBox1->Items ->Add(textBox1->Text );

textBox1->Text="";

       }

private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)

     {

       int numListBoxItems;

numListBoxItems=listBox1->Items ->Count;

label2->Text=numListBoxItems.ToString() ;

     }

private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e)

     {

       int position;

String ^myString;

myString=textBox2->Text;

position=listBox1->Items->IndexOf(myString);

label4->Text=position.ToString();

     }

private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e)

     {

       String ^newWord;

int position;

newWord=textBox3->Text;

position=Int32::Parse(textBox4->Text);

listBox1->Items->Insert(position, newWord);

     }

private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e)

     {

       listBox1->Sorted=true;

     }

private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e)

     {

       String ^myString;

myString=textBox5->Text;

listBox1->Items->Remove(myString);

     }

private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e)

     {

       int position;

String ^myString;

myString=textBox6->Text;

position=Int32::Parse(myString);

listBox1->Items->RemoveAt(position);

     }

private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {

     }

      Note: If you lose the design window (which often happens when you open the “sln”  file using explorer) try the following: 

      Navigate to File > New > Project  > Window Form Application

       To make a design window appear which shows the forms go to view > designer

(Back) 


Tutorial 4: Simple Animation, Which Shows the Use of the Timer and Location Commands Using Visual C++.NET 2010, 2008

       This tutorial will show how to move a control button around the form employing the timer.  It also shows something about how placement works and the coordinate system of the form. Click here for the source code to the Simple Animation Program in Visual C++.NET for the 2010 version or click here to download the 2008 version. Make the form size 286, 314. Begin by designing a form which looks as follows:       

Basic animation with timers in a Microsoft Visual C++ Program

Set the timer's enabled property to false. Then code the following to the buttons:

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)

       {

         button1->Visible=false;

button2->Visible=true;

timer1->Enabled=true;

timer1->Interval=30;

       }

   private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)

       {

         timer1->Enabled=false;

button1->Visible=true;

       }

   private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)

       {

         static bool NE, NW, SW, SE;

         static int x, y;

         label1->Text=x.ToString();

         if (NE == false && NW == false && SW == false && SE== false)

         {

           x=8;

           y=64;

           SE=true;

         }

         if (NE)

         {

           x=x+4;

           y=y-4;

           if (x>=220)

           {

             SW=false;

             NE=false;

             NW=true;

             SE=false;

           }

           if (y<=0)

           {

             SW=false;

             NE=false;

             NW=false;

             SE=true;

           }

          }

 

         //*********************

         if (SE)

         {

           x=x+4;

           y=y+4;

           if (x>=220)

           {

             SW=true;

             NE=false;

             NW=false;

             SE=false;

           }

           if (y>=250)

           {

             SW=false;

             NE=true;

             NW=false;

             SE=false;

           }

         }

         //**********************

         if (SW)

         {

           x=x-4;

           y=y+4;

           if (x<=0)

           {

             SW=false;

             NE=false;

             NW=false;

             SE=true;

           }

           if (y>=250)

           {

             SW=false;

             NE=false;

             NW=true;

             SE=false;

           }

         }

         //************************

         if (NW)

         {

           x=x-4;

           y=y-4;

           if (x<=0)

           {

             SW=false;

             NE=true;

             NW=false;

             SE=false;

           }

           if (y<=0)

           {

             SW=true;

             NE=false;

             NW=false;

             SE=false;

           }

         }

         button2->Location=System::Drawing::Point(x,y);

       }

     private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)

         {

         }

 

   (Back) 


Tutorial 5 : Menus Using Visual C++.NET 2010, 2008

        In this tutorial you will add a Menu to make button and textbox appear. Click here for the source code to the Menus Program in Visual C++.NET for the 2010 version or click here to download the 2008 version. To add a menu to your form go to the toolBox and double Click on the the mainMenu tool. This will add a menu to your form. Then type "&File" where it says "Type Here", which add File to the Menu. Then in the box below "File" type "&Make Button Appear" and then "M&ake TextBox Appear", then a lone hyphen (-), and then E&xit. The form should look something like this:   

Menus and Visibility

        Then add the following code to the appropriate item in the menu by double clicking on this item to get to its Code Window. To add code to specific menu items, double click on the menu item to bring up the code window.:

private: System::Void makeButtonAppearToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e)

     {

       button1->Visible=true;

     }

private: System::Void makeToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e)

     {

       textBox1->Visible=true;

     }

private: System::Void exitToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e)

     {

       System::Environment::Exit(System::Environment::ExitCode);

     }

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)

     {

       button1->Visible=false;

       textBox1->Visible=false;

     }

 

(Back) 


Tutorial 6 : File Saving, Opening and Using Common Dialog Boxes Using Visual C++.NET 2010, 2008

        This program will show you how to save to file, open from file and how to use dialog boxes to perform these tasks. Click here for the source code to the File Saving, Opening Program in Visual C++.NET for the 2010 version or click here to download the 2008 version. Begin by placing a text file call "myfile.txt" in your inner-most debug directory with a few lines of text placed in it of your choosing. Make this file in Visual Studio by going to >File>New>File>General>Text File. Place this file in the directory with the source (.cpp) you are creating. Then design a form which looks as follow with a listbox to the left and a textBox to the right with multiline property selected. Add a openFileDialog and a saveFileDialog tool to your form. To the right of the listbox is a textbox with its multiline property selected.   

File Opening and Saving Common Dialog Boxes

        Add to the namespace region:

    using namespace System::IO;

        Add the following code to the relevant buttons: 

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)

     {

       try

         {

           FileStream ^fileInput = gcnew FileStream("myfile.txt", FileMode::OpenOrCreate, FileAccess::ReadWrite);

           StreamReader ^streamIn = gcnew StreamReader(fileInput);

           while(!streamIn->EndOfStream)

           {

             listBox1->Items->Add(streamIn->ReadLine());

           };

           streamIn->Close();

         }

         catch(IOException ^)

         {

           textBox1->Text="something went wrong";

         }

     }

private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)

     {

       try

       {

         FileStream ^outFile = gcnew FileStream("mynewfile.txt", FileMode::Create, FileAccess::Write);

         StreamWriter ^streamOut = gcnew StreamWriter(outFile);

         streamOut->WriteLine(textBox1->Text);

         streamOut->Close();

       }

       catch(IOException ^)

       {

         textBox1->Text="something went wrong";

       }

     }

private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e)

     {

       String ^myfile = "";

       openFileDialog1->ShowDialog() ;

       myfile = openFileDialog1->FileName;

       try

       {

         FileStream ^fileInput = gcnew FileStream(myfile, FileMode::OpenOrCreate, FileAccess::ReadWrite);

         StreamReader ^streamIn = gcnew StreamReader(fileInput);

         while(!streamIn->EndOfStream)

         {

           listBox1->Items->Add(streamIn->ReadLine());

         };

         streamIn->Close();

       }

       catch(IOException ^)

       {

         textBox1->Text="something went wrong";

       }

     }

private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e)

     {

       String ^myfile = "";

       saveFileDialog1->ShowDialog() ;

       myfile = saveFileDialog1->FileName;

       try

       {

         FileStream ^outFile = gcnew FileStream(myfile, FileMode::Create, FileAccess::Write);

         StreamWriter ^streamOut = gcnew StreamWriter(outFile);

         streamOut->WriteLine(textBox1->Text);

         streamOut->Close();

       }

       catch(IOException ^)

       {

         textBox1->Text="something went wrong";

       }

     }

private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e)

     {

       try

       {

         FileStream ^outFile = gcnew FileStream("myfile.txt", FileMode::Append, FileAccess::Write);

         StreamWriter ^streamOut = gcnew StreamWriter(outFile);

         streamOut->WriteLine(textBox1->Text);

         streamOut->Close();

       }

       catch(IOException ^)

       {

         textBox1->Text="something went wrong";

       }

     }

 

(Back) 


Tutorial 7: Concatenating Strings Together in the Windows C++ Environment using Visual C++.NET 2010, 2008:

        This program will show how to put two strings together to create a combination of the two. This called concatenation. Click here for the source code to the Concatenating Program in Visual C++.NET for the 2010 version or click here to download the 2008 version. Below the button is a label with its autosize property set to false. Make your form look something like this:   

Concatenating strings in Visual Microsoft Programs

Add the following code to the button: 

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)

       {

         String ^strCat;

         String ^something=textBox1->Text;

         String ^somethingElse=textBox2->Text;

         strCat=something+" "+somethingElse;

         label3->Text=strCat;

       }

 

(Back) 


Tutorial 8 : Detecting Asynchronous Keys Using Visual C++.NET 2010, 2008

        This project will allow you to move a label around your form using Asynchronous Keys.  Click here for the source code to the Asynchronous Keys Program in Visual C++.NET for the 2010 version or click here for the 2008 version of the source and the project. It is called asynchronous because more than one key can be pressed at a time and it will be recognized. This is usually something that isn't allowed. First set up your form to look as follows (and yes a timer needs to be added). You must include the dynamic link library user32.dll for this program to allow the asynchronous reading of key presses. 

Asynchronous Key Detection

        Enable the timer.. Next code the following, add everything in bright red: 

#pragma once

#include<windows.h>

#include<time.h>

#pragma comment(lib, "user32")

 

 

namespace AsynchronousKeys {  

 

   using namespace System;

   using namespace System::ComponentModel;

   using namespace System::Collections;

   using namespace System::Windows::Forms;

   using namespace System::Data;

   using namespace System::Drawing;

 

   publicrefclass Form1 : public System::Windows::Forms::Form

   {

   public:

     Form1(void)

     {

#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0 )

       InitializeComponent();

     }

 

   protected:

     ~Form1()

     {

       if (components)

       {

         delete components;

       }

     }

   private: System::Windows::Forms::Label^ label1;

   private: System::Windows::Forms::Timer^ timer1;

   private: System::ComponentModel::IContainer^ components;

   protected:

 

   private:

 

#pragma region Windows Form Designer generated code

     void InitializeComponent(void)

     {

       this->components = (gcnew System::ComponentModel::Container());

       this->label1 = (gcnew System::Windows::Forms::Label());

       this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));

       this->SuspendLayout();

       this->label1->AutoSize = true;

       this->label1->Location = System::Drawing::Point(144, 29);

       this->label1->Name = L"label1";

       this->label1->Size = System::Drawing::Size(35, 13);

       this->label1->TabIndex = 0;

       this->label1->Text = L"label1";

       this->timer1->Enabled = true;

       this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);

       this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);

       this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

       this->ClientSize = System::Drawing::Size(292, 105);

        this->Controls->Add(this->label1);

       this->Name = L"Form1";

       this->Text = L"Form1";

       this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

       this->ResumeLayout(false);

       this->PerformLayout();

     }

#pragma endregion

   private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {

       }

   private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)

       {

         if (KEY_DOWN(VK_LEFT))

           label1->Text="left";

         if (KEY_DOWN(VK_RIGHT))

            label1->Text="right";

         if (KEY_DOWN(VK_UP))

           label1->Text="up";

         if (KEY_DOWN(VK_DOWN))

           label1->Text="down";

         if (KEY_DOWN(VK_SPACE))

           label1->Text="space";

         if (KEY_DOWN(VK_ESCAPE))

           label1->Text="escape";

         if (KEY_DOWN(65))

           label1->Text="A";

         if (KEY_DOWN(90))

           label1->Text="Z";

       }

   };

}

(Back) 


Tutorial 9: Using Arrays of Strings Using Visual C++.NET 2010

        In this tutorial you will see how to create arrays of strings. Click here for the source code to the Arrays of Strings Program in Visual C++.NET for the 2010. Make a form which looks as follows and code what is in bright red:

Arrays of Strings

        Insert the following code:

#pragma once

 

namespace StringArrays {

 

       using namespace System;

       using namespace System::ComponentModel;

       using namespace System::Collections;

       using namespace System::Windows::Forms;

       using namespace System::Data;

       using namespace System::Drawing;

 

       /// <summary>

       /// Summary for Form1

       /// </summary>

       public ref class Form1 : public System::Windows::Forms::Form

       {

              static array<String^>^ first = gcnew array<String^>(100);

              static array<String^>^ last = gcnew array<String^>(100);

           static int i=0;

 

 

       public:

              Form1(void)

              {

                     InitializeComponent();

                     //

                     //TODO: Add the constructor code here

                     //

              }

 

       protected:

              /// <summary>

              /// Clean up any resources being used.

              /// </summary>

              ~Form1()

              {

                     if (components)

                     {

                           delete components;

                     }

              }

       private: System::Windows::Forms::Label^  label1;

       protected:

       private: System::Windows::Forms::TextBox^  textBox1;

       private: System::Windows::Forms::TextBox^  textBox2;

       private: System::Windows::Forms::Label^  label2;

       private: System::Windows::Forms::Button^  button1;

       private: System::Windows::Forms::Button^  button2;

       private: System::Windows::Forms::TextBox^  textBox3;

       private: System::Windows::Forms::ListBox^  listBox1;

 

       private:

              /// <summary>

              /// Required designer variable.

              /// </summary>

              System::ComponentModel::Container ^components;

 

#pragma region Windows Form Designer generated code

              /// <summary>

              /// Required method for Designer support - do not modify

              /// the contents of this method with the code editor.

              /// </summary>

              void InitializeComponent(void)

              {

                     this->label1 = (gcnew System::Windows::Forms::Label());

                     this->textBox1 = (gcnew System::Windows::Forms::TextBox());

                     this->textBox2 = (gcnew System::Windows::Forms::TextBox());

                     this->label2 = (gcnew System::Windows::Forms::Label());

                     this->button1 = (gcnew System::Windows::Forms::Button());

                     this->button2 = (gcnew System::Windows::Forms::Button());

                     this->textBox3 = (gcnew System::Windows::Forms::TextBox());

                     this->listBox1 = (gcnew System::Windows::Forms::ListBox());

                     this->SuspendLayout();

                     //

                     // label1

                     //

                     this->label1->AutoSize = true;

                     this->label1->Location = System::Drawing::Point(37, 25);

                     this->label1->Name = L"label1";

                     this->label1->Size = System::Drawing::Size(26, 13);

                     this->label1->TabIndex = 0;

                     this->label1->Text = L"First";

                     //

                     // textBox1

                     //

                     this->textBox1->Location = System::Drawing::Point(40, 41);

                     this->textBox1->Name = L"textBox1";

                     this->textBox1->Size = System::Drawing::Size(84, 20);

                     this->textBox1->TabIndex = 1;

                     //

                     // textBox2

                     //

                     this->textBox2->Location = System::Drawing::Point(40, 92);

                     this->textBox2->Name = L"textBox2";

                     this->textBox2->Size = System::Drawing::Size(84, 20);

                     this->textBox2->TabIndex = 3;

                     //

                     // label2

                     //

                     this->label2->AutoSize = true;

                     this->label2->Location = System::Drawing::Point(37, 76);

                     this->label2->Name = L"label2";

                     this->label2->Size = System::Drawing::Size(27, 13);

                     this->label2->TabIndex = 2;

                     this->label2->Text = L"Last";

                     //

                     // button1

                     //

                     this->button1->Location = System::Drawing::Point(147, 34);

                     this->button1->Name = L"button1";

                     this->button1->Size = System::Drawing::Size(91, 26);

                     this->button1->TabIndex = 4;

                     this->button1->Text = L"Enter Names";

                     this->button1->UseVisualStyleBackColor = true;

                     this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);

                     //

                     // button2

                     //

                     this->button2->Location = System::Drawing::Point(147, 69);

                     this->button2->Name = L"button2";

                     this->button2->Size = System::Drawing::Size(91, 26);

                     this->button2->TabIndex = 5;

                     this->button2->Text = L"Enter Index";

                     this->button2->UseVisualStyleBackColor = true;

                     this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);

                     //

                     // textBox3

                     //

                     this->textBox3->Location = System::Drawing::Point(154, 124);

                     this->textBox3->Name = L"textBox3";

                     this->textBox3->Size = System::Drawing::Size(84, 20);

                     this->textBox3->TabIndex = 6;

                     //

                     // listBox1

                     //

                     this->listBox1->FormattingEnabled = true;

                     this->listBox1->Location = System::Drawing::Point(272, 24);

                     this->listBox1->Name = L"listBox1";

                     this->listBox1->Size = System::Drawing::Size(120, 147);

                     this->listBox1->TabIndex = 7;

                     //

                     // Form1

                     //

                     this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);

                     this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

                     this->ClientSize = System::Drawing::Size(420, 208);

                     this->Controls->Add(this->listBox1);

                     this->Controls->Add(this->textBox3);

                     this->Controls->Add(this->button2);

                     this->Controls->Add(this->button1);

                     this->Controls->Add(this->textBox2);

                     this->Controls->Add(this->label2);

                     this->Controls->Add(this->textBox1);

                     this->Controls->Add(this->label1);

                     this->Name = L"Form1";

                     this->Text = L"Form1";

                     this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

                     this->ResumeLayout(false);

                     this->PerformLayout();

 

              }

#pragma endregion

       private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)

                      {

                            first[i]=textBox1->Text;

                            last[i]=textBox2->Text;

                       listBox1->Items->Add(first[i]);

                            listBox1->Items->Add(last[i]);

                            textBox1->Text="";

                            textBox2->Text="";

                       textBox1->Focus();

                       i++;

                      }

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      int index;

                      String ^temp;

                      temp=textBox3->Text;

                      index=Int32::Parse(temp);

 

 

                 textBox1->Text=first[index];

                 textBox2->Text=last[index];

 

                i++;

               }

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

               }

};

}

 (Back) 


Tutorial 10: Using SQL to Search and Modify an Access Database In Visual C++.NET 2008, 2010 (Updated 12/11/2011)

Click here for the source code to the Concatenating Program in Visual C++.NET for the 2010 version or click here to download the 2008 version. This program shows how to create a simple database program, which uses odbcad32, and an oleDataAdapter to hook up to a Access 2010 database using SQL commands. This program will not use the Data Sources window found in Visual Basic, which probably doesn't exist in Visual C++.NET 2010. First, open Microsoft Access (if you do not have Access 2007 use Access 2005, or a supplied database) and select new blank database. You can download a free redistributable version of Access at http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=10910   You may also need the Access database engine at http://www.microsoft.com/downloads/en/details.aspx?displaylang=en&FamilyID=c06b8369-60dd-4b64-a44b-84b371ede16d . You may not be able to directly make tables with what is provided in the links, but you will be able to access my database in the sample project. Depending on what version of Windows you have you may have to make some adjustments. There is an issue with 64 bit vs. 32 bit Windows7 (refer to http://support.microsoft.com/kb/942976) which says if you use a 64 bit operating system you must have a 32 bit datasource (database). The code here works in the 32 bit environment. If you wish to go to the 64 bit environment, it has been reported that if you use an older mdb database that you may be able to overcome this issue. Both PhoneBook.accdb written in Access 2010 format and PhoneBook.mdb written in a 2003 format are included in this project as well as all the graphics.

Create a directory called download on your c: drive in the root and save the file as PhoneBook.accdb

To create fields in access for the first name and last name be careful. If you choose a key word in Access the program won't. Specifically it turns out first and last have become key words. For a list of key words that you can't use as column names refer to http://sqlserver2000.databases.aspfaq.com/what-are-reserved-access-odbc-and-sql-server-keywords.html . So make the columns LastName, FirstName, Phone, and fill in as follows:

 

Try to exit Acess after you have entered your data and it will present the following, save this as is as Table1

Alternative:  Save the program as a 2002-2003 mdb database:

This should look as follows:

 When you finish entering your data go to file and save the table as Table1 (the default).  Say yes to creating a primary field.  Since it matters where you put your database, it is easiest to put it in the root of your C:\ drive after you have created it.  Also be careful, databases may be case sensitive.  Close Access and your database before going on!

Open My Computer or Windows Explorer, navigate to the C:\windows\system32  and search for odbcad32.exe.  Right click on this file as follows and select >send to>desktop.

Double click on the odbcad32.exe icon which will start the ODBC Data Source Administrator.  Select the System DSN tab and Add

 

In Create New Data Source select Microsoft Access Driver (*.mdb, *.accdb) as shown and click Finish.

In the ODBC Microsoft Access Setup Window enter PhoneBook under Data Source Name, leave description blank, and click Select.

Navigate to and select your phonebook.mdb in the root of your c: drive and click OK.

Click OK under ODBC Microsoft Access Setup

This completes configuring the ODBC Administrator so your program will be able access the database.  Design a form that looks as follows called NamesDBProgram3 (the large white field in the program below is a textbox with it multi-line function set to true).

Go to the tool box and under data items right click, and select choose items as shown below. Add an oleDataAdapter to your form as follows:

Under the .NET Framework Components select OleDbDataAdapter as shown below

 

This will add a OleDbDataAdapter to the toolbox. Add the OleDBDataAdapter to your form which will trigger the following window. Select New Connection.

Data Adapter Configuration Wizard

This will trigger the appearance of the following dialog window:

Add Connection

Select Change, which will cause the following window to appear and select “Microsoft Access Database File” and then OK.

  Change Data Source

This will cause you to return to the Add Connection Dialog which looks as follows. 

Add Connection

Click Browse and navigate to and select phonebook.accdb and click Open.   

Don’t include a password but leave Admin as shown.  Click on test connection and make sure a connection to the database exists. Then click OK.  Back at the wizard click OK.

In the Data Adapter Configuration Wizard click Next.

In the following dialog window select Use SQL statements. 

Data Adapter Configuration Wizard...Use SQL

In the next window click on Query Builder… 

Generate SQL Statements

In the next dialog window select Add, then close this “Add Table Window and then click close.

Add Table

Click close to Add Table, and in Query Builder select All Columns, ID, lastName, firstName, and Phone and click on OK.

This should lead to the dialog box.  Click Finish

 

Your design window in Visual C++ should now look as follows:

        If something goes wrong in setting up your database, it is very, very difficult to fix.   If you do have to change something, you may have to go to view, select Server Explorer, right click on the database you just configured and select delete.  Then remove the related objects on your form.  If this doesn’t clean things out so you get the above window you may have to close your project, open a new one and start over.  It may even be necessary to reboot your computer.

Add the following lines of code. I have high lighted in yellow some lines that are easy to miss. Make sure to get the code to the form load event and the buttons.

#pragma once

 

namespace NamesDBProgram {

 

       using namespace System;

       using namespace System::ComponentModel;

       using namespace System::Collections;

       using namespace System::Windows::Forms;

       using namespace System::Data;

       using namespace System::Drawing;

       using namespace System::Data::OleDb;

 

       /// <summary>

       /// Summary for Form1

       ///

       /// WARNING: If you change the name of this class, you will need to change the

       ///          'Resource File Name' property for the managed resource compiler tool

       ///          associated with all .resx files this class depends on.  Otherwise,

       ///          the designers will not be able to interact properly with localized

       ///          resources associated with this form.

       /// </summary>

       public ref class Form1 : public System::Windows::Forms::Form

       {

       public:

              static String ^findFirst="";

              static String ^findLast="";

              static bool foundJustUsed=false;

              Form1(void)

              {

                     InitializeComponent();

                     //

                     //TODO: Add the constructor code here

                     //

              }

 

       protected:

              /// <summary>

              /// Clean up any resources being used.

              /// </summary>

              ~Form1()

              {

                     if (components)

                     {

                           delete components;

                     }

              }

 

       protected:

       private: System::Windows::Forms::Label^  label7;

       private: System::Windows::Forms::Button^  button4;

       private: System::Windows::Forms::Label^  label6;

       private: System::Windows::Forms::Button^  button3;

       private: System::Windows::Forms::Label^  label5;

       private: System::Windows::Forms::Label^  label4;

       private: System::Windows::Forms::Button^  button2;

       private: System::Windows::Forms::TextBox^  textBox4;

       private: System::Windows::Forms::Button^  button1;

       private: System::Windows::Forms::TextBox^  textBox3;

       private: System::Windows::Forms::Label^  label3;

       private: System::Windows::Forms::TextBox^  textBox2;

       private: System::Windows::Forms::Label^  label2;

       private: System::Windows::Forms::TextBox^  textBox1;

       private: System::Windows::Forms::Label^  label1;

       private: System::Data::OleDb::OleDbCommand^  oleDbSelectCommand1;

       private: System::Data::OleDb::OleDbCommand^  oleDbInsertCommand1;

       private: System::Data::OleDb::OleDbCommand^  oleDbUpdateCommand1;

       private: System::Data::OleDb::OleDbCommand^  oleDbDeleteCommand1;

       private: System::Data::OleDb::OleDbDataAdapter^  oleDbDataAdapter1;

       private: System::Data::OleDb::OleDbConnection^  oleDbConnection1;

       private: System::ComponentModel::IContainer^  components;

 

       private:

              /// <summary>

              /// Required designer variable.

              /// </summary>

 

 

#pragma region Windows Form Designer generated code

              /// <summary>

              /// Required method for Designer support - do not modify

              /// the contents of this method with the code editor.

              /// </summary>

              void InitializeComponent(void)

              {

                     System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));

                     this->label7 = (gcnew System::Windows::Forms::Label());

                     this->button4 = (gcnew System::Windows::Forms::Button());

                     this->label6 = (gcnew System::Windows::Forms::Label());

                     this->button3 = (gcnew System::Windows::Forms::Button());

                     this->label5 = (gcnew System::Windows::Forms::Label());

                     this->label4 = (gcnew System::Windows::Forms::Label());

                     this->button2 = (gcnew System::Windows::Forms::Button());

                     this->textBox4 = (gcnew System::Windows::Forms::TextBox());

                     this->button1 = (gcnew System::Windows::Forms::Button());

                     this->textBox3 = (gcnew System::Windows::Forms::TextBox());

                     this->label3 = (gcnew System::Windows::Forms::Label());

                     this->textBox2 = (gcnew System::Windows::Forms::TextBox());

                     this->label2 = (gcnew System::Windows::Forms::Label());

                     this->textBox1 = (gcnew System::Windows::Forms::TextBox());

                     this->label1 = (gcnew System::Windows::Forms::Label());

                     this->oleDbSelectCommand1 = (gcnew System::Data::OleDb::OleDbCommand());

                     this->oleDbConnection1 = (gcnew System::Data::OleDb::OleDbConnection());

                     this->oleDbInsertCommand1 = (gcnew System::Data::OleDb::OleDbCommand());

                     this->oleDbUpdateCommand1 = (gcnew System::Data::OleDb::OleDbCommand());

                     this->oleDbDeleteCommand1 = (gcnew System::Data::OleDb::OleDbCommand());

                     this->oleDbDataAdapter1 = (gcnew System::Data::OleDb::OleDbDataAdapter());

                     this->SuspendLayout();

                     //

                     // label7

                     //

                     this->label7->Location = System::Drawing::Point(273, 20);

                     this->label7->Name = L"label7";

                     this->label7->Size = System::Drawing::Size(150, 43);

                     this->label7->TabIndex = 32;

                     this->label7->Text = L"First do a find, then change First, Last, Phone as needed and press update";

                     //

                     // button4

                     //

                     this->button4->Location = System::Drawing::Point(317, 66);

                     this->button4->Name = L"button4";

                     this->button4->Size = System::Drawing::Size(84, 25);

                     this->button4->TabIndex = 31;

                     this->button4->Text = L"Update";

                     this->button4->UseVisualStyleBackColor = true;

                     this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click);

                     //

                     // label6

                     //

                     this->label6->AutoSize = true;

                     this->label6->Location = System::Drawing::Point(150, 112);

                     this->label6->Name = L"label6";

                     this->label6->Size = System::Drawing::Size(126, 13);

                     this->label6->TabIndex = 30;

                     this->label6->Text = L"Enter First, Last to Delete";

                     //

                     // button3

                     //

                     this->button3->Location = System::Drawing::Point(153, 134);

                     this->button3->Name = L"button3";

                     this->button3->Size = System::Drawing::Size(84, 25);

                     this->button3->TabIndex = 29;

                     this->button3->Text = L"Delete";

                     this->button3->UseVisualStyleBackColor = true;

                     this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);

                     //

                     // label5

                     //

                     this->label5->AutoSize = true;

                     this->label5->Location = System::Drawing::Point(150, 66);

                     this->label5->Name = L"label5";

                     this->label5->Size = System::Drawing::Size(129, 13);

                     this->label5->TabIndex = 28;

                     this->label5->Text = L"Enter First, Last for Phone";

                     //

                     // label4

                     //

                     this->label4->AutoSize = true;

                     this->label4->Location = System::Drawing::Point(150, 14);

                     this->label4->Name = L"label4";

                     this->label4->Size = System::Drawing::Size(117, 13);

                     this->label4->TabIndex = 27;

                     this->label4->Text = L"Enter First, Last, Phone";

                     //

                     // button2

                     //

                     this->button2->Location = System::Drawing::Point(153, 82);

                     this->button2->Name = L"button2";

                     this->button2->Size = System::Drawing::Size(84, 25);

                     this->button2->TabIndex = 26;

                     this->button2->Text = L"Find";

                     this->button2->UseVisualStyleBackColor = true;

                     this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);

                     //

                     // textBox4

                     //

                     this->textBox4->Location = System::Drawing::Point(208, 176);

                     this->textBox4->Multiline = true;

                     this->textBox4->Name = L"textBox4";

                     this->textBox4->Size = System::Drawing::Size(131, 115);

                     this->textBox4->TabIndex = 25;

                     //

                     // button1

                     //

                     this->button1->Location = System::Drawing::Point(153, 36);

                     this->button1->Name = L"button1";

                     this->button1->Size = System::Drawing::Size(84, 25);

                     this->button1->TabIndex = 24;

                     this->button1->Text = L"Insert\r\n";

                     this->button1->UseVisualStyleBackColor = true;

                     this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);

                     //

                     // textBox3

                     //

                     this->textBox3->Location = System::Drawing::Point(55, 105);

                     this->textBox3->Name = L"textBox3";

                     this->textBox3->Size = System::Drawing::Size(75, 20);

                     this->textBox3->TabIndex = 23;

                     //

                     // label3

                     //

                     this->label3->AutoSize = true;

                     this->label3->Location = System::Drawing::Point(11, 108);

                     this->label3->Name = L"label3";

                     this->label3->Size = System::Drawing::Size(38, 13);

                     this->label3->TabIndex = 22;

                     this->label3->Text = L"Phone";

                     //

                     // textBox2

                     //

                     this->textBox2->Location = System::Drawing::Point(55, 72);

                     this->textBox2->Name = L"textBox2";

                     this->textBox2->Size = System::Drawing::Size(75, 20);

                     this->textBox2->TabIndex = 21;

                     //

                     // label2

                     //

                     this->label2->AutoSize = true;

                     this->label2->Location = System::Drawing::Point(22, 72);

                     this->label2->Name = L"label2";

                     this->label2->Size = System::Drawing::Size(27, 13);

                     this->label2->TabIndex = 20;

                     this->label2->Text = L"Last";

                     //

                     // textBox1

                     //

                     this->textBox1->Location = System::Drawing::Point(55, 39);

                     this->textBox1->Name = L"textBox1";

                     this->textBox1->Size = System::Drawing::Size(75, 20);

                     this->textBox1->TabIndex = 19;

                     //

                     // label1

                     //

                     this->label1->AutoSize = true;

                     this->label1->Location = System::Drawing::Point(23, 42);

                     this->label1->Name = L"label1";

                     this->label1->Size = System::Drawing::Size(26, 13);

                     this->label1->TabIndex = 18;

                     this->label1->Text = L"First";

                     //

                     // oleDbSelectCommand1

                     //

                     this->oleDbSelectCommand1->CommandText = L"SELECT     Table1.*, ID AS Expr1, lastName AS Expr2, firstName AS Expr3, phone AS"

                           L" Expr4\r\nFROM         Table1";

                     this->oleDbSelectCommand1->Connection = this->oleDbConnection1;

                     //

                     // oleDbConnection1

                     //

                     this->oleDbConnection1->ConnectionString = L"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\PhoneBook.accdb";

                     //

                     // oleDbInsertCommand1

                     //

                     this->oleDbInsertCommand1->CommandText = L"INSERT INTO `Table1` (`lastName`, `firstName`, `phone`, `lastName`, `firstName`, "

                           L"`phone`) VALUES (\?, \?, \?, \?, \?, \?)";

                     this->oleDbInsertCommand1->Connection = this->oleDbConnection1;

                     this->oleDbInsertCommand1->Parameters->AddRange(gcnew cli::array< System::Data::OleDb::OleDbParameter^  >(6) {(gcnew System::Data::OleDb::OleDbParameter(L"lastName",

                           System::Data::OleDb::OleDbType::VarWChar, 0, L"lastName")), (gcnew System::Data::OleDb::OleDbParameter(L"firstName", System::Data::OleDb::OleDbType::VarWChar,

                           0, L"firstName")), (gcnew System::Data::OleDb::OleDbParameter(L"phone", System::Data::OleDb::OleDbType::VarWChar, 0, L"phone")),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Expr2", System::Data::OleDb::OleDbType::VarWChar, 0, L"Expr2")), (gcnew System::Data::OleDb::OleDbParameter(L"Expr3",

                           System::Data::OleDb::OleDbType::VarWChar, 0, L"Expr3")), (gcnew System::Data::OleDb::OleDbParameter(L"Expr4", System::Data::OleDb::OleDbType::VarWChar,

                           0, L"Expr4"))});

                     //

                     // oleDbUpdateCommand1

                     //

                     this->oleDbUpdateCommand1->CommandText = resources->GetString(L"oleDbUpdateCommand1.CommandText");

                     this->oleDbUpdateCommand1->Connection = this->oleDbConnection1;

                     this->oleDbUpdateCommand1->Parameters->AddRange(gcnew cli::array< System::Data::OleDb::OleDbParameter^  >(21) {(gcnew System::Data::OleDb::OleDbParameter(L"lastName",

                           System::Data::OleDb::OleDbType::VarWChar, 0, L"lastName")), (gcnew System::Data::OleDb::OleDbParameter(L"firstName", System::Data::OleDb::OleDbType::VarWChar,

                           0, L"firstName")), (gcnew System::Data::OleDb::OleDbParameter(L"phone", System::Data::OleDb::OleDbType::VarWChar, 0, L"phone")),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Expr2", System::Data::OleDb::OleDbType::VarWChar, 0, L"Expr2")), (gcnew System::Data::OleDb::OleDbParameter(L"Expr3",

                           System::Data::OleDb::OleDbType::VarWChar, 0, L"Expr3")), (gcnew System::Data::OleDb::OleDbParameter(L"Expr4", System::Data::OleDb::OleDbType::VarWChar,

                           0, L"Expr4")), (gcnew System::Data::OleDb::OleDbParameter(L"Original_ID", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           false, static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"ID", System::Data::DataRowVersion::Original, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_lastName", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"lastName", System::Data::DataRowVersion::Original, true, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Original_lastName", System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input,

                           false, static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"lastName", System::Data::DataRowVersion::Original, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_firstName", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"firstName", System::Data::DataRowVersion::Original, true, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Original_firstName", System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input,

                           false, static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"firstName", System::Data::DataRowVersion::Original,

                           nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_phone", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"phone", System::Data::DataRowVersion::Original, true, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Original_phone", System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input,

                           false, static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"phone", System::Data::DataRowVersion::Original, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_Expr1", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"Expr1", System::Data::DataRowVersion::Original, true, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Original_Expr1", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           false, static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"Expr1", System::Data::DataRowVersion::Original, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_Expr2", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"Expr2", System::Data::DataRowVersion::Original, true, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Original_Expr2", System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input,

                           false, static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"Expr2", System::Data::DataRowVersion::Original, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_Expr3", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"Expr3", System::Data::DataRowVersion::Original, true, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Original_Expr3", System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input,

                           false, static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"Expr3", System::Data::DataRowVersion::Original, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_Expr4", System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input,

                           static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"Expr4", System::Data::DataRowVersion::Original, true, nullptr)),

                           (gcnew System::Data::OleDb::OleDbParameter(L"Original_Expr4", System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input,

                           false, static_cast<System::Byte>(0), static_cast<System::Byte>(0), L"Expr4", System::Data::DataRowVersion::Original, nullptr))});

                     //

                     // oleDbDeleteCommand1

                     //

                     this->oleDbDeleteCommand1->CommandText = resources->GetString(L"oleDbDeleteCommand1.CommandText");

                     this->oleDbDeleteCommand1->Connection = this->oleDbConnection1;

                     this->oleDbDeleteCommand1->Parameters->AddRange(gcnew cli::array< System::Data::OleDb::OleDbParameter^  >(15) {(gcnew System::Data::OleDb::OleDbParameter(L"Original_ID",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, false, static_cast<System::Byte>(0),

                           static_cast<System::Byte>(0), L"ID", System::Data::DataRowVersion::Original, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_lastName",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, static_cast<System::Byte>(0), static_cast<System::Byte>(0),

                           L"lastName", System::Data::DataRowVersion::Original, true, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"Original_lastName",

                           System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input, false, static_cast<System::Byte>(0),

                           static_cast<System::Byte>(0), L"lastName", System::Data::DataRowVersion::Original, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_firstName",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, static_cast<System::Byte>(0), static_cast<System::Byte>(0),

                           L"firstName", System::Data::DataRowVersion::Original, true, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"Original_firstName",

                           System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input, false, static_cast<System::Byte>(0),

                           static_cast<System::Byte>(0), L"firstName", System::Data::DataRowVersion::Original, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_phone",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, static_cast<System::Byte>(0), static_cast<System::Byte>(0),

                           L"phone", System::Data::DataRowVersion::Original, true, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"Original_phone",

                           System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input, false, static_cast<System::Byte>(0),

                            static_cast<System::Byte>(0), L"phone", System::Data::DataRowVersion::Original, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_Expr1",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, static_cast<System::Byte>(0), static_cast<System::Byte>(0),

                           L"Expr1", System::Data::DataRowVersion::Original, true, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"Original_Expr1",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, false, static_cast<System::Byte>(0),

                           static_cast<System::Byte>(0), L"Expr1", System::Data::DataRowVersion::Original, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_Expr2",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, static_cast<System::Byte>(0), static_cast<System::Byte>(0),

                           L"Expr2", System::Data::DataRowVersion::Original, true, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"Original_Expr2",

                           System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input, false, static_cast<System::Byte>(0),

                           static_cast<System::Byte>(0), L"Expr2", System::Data::DataRowVersion::Original, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_Expr3",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, static_cast<System::Byte>(0), static_cast<System::Byte>(0),

                           L"Expr3", System::Data::DataRowVersion::Original, true, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"Original_Expr3",

                           System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input, false, static_cast<System::Byte>(0),

                           static_cast<System::Byte>(0), L"Expr3", System::Data::DataRowVersion::Original, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"IsNull_Expr4",

                           System::Data::OleDb::OleDbType::Integer, 0, System::Data::ParameterDirection::Input, static_cast<System::Byte>(0), static_cast<System::Byte>(0),

                           L"Expr4", System::Data::DataRowVersion::Original, true, nullptr)), (gcnew System::Data::OleDb::OleDbParameter(L"Original_Expr4",

                           System::Data::OleDb::OleDbType::VarWChar, 0, System::Data::ParameterDirection::Input, false, static_cast<System::Byte>(0),

                           static_cast<System::Byte>(0), L"Expr4", System::Data::DataRowVersion::Original, nullptr))});

                     //

                     // oleDbDataAdapter1

                     //

                     this->oleDbDataAdapter1->DeleteCommand = this->oleDbDeleteCommand1;

                     this->oleDbDataAdapter1->InsertCommand = this->oleDbInsertCommand1;

                     this->oleDbDataAdapter1->SelectCommand = this->oleDbSelectCommand1;

                     cli::array< System::Data::Common::DataColumnMapping^ >^ __mcTemp__1 = gcnew cli::array< System::Data::Common::DataColumnMapping^  >(8) {(gcnew System::Data::Common::DataColumnMapping(L"ID",

                           L"ID")), (gcnew System::Data::Common::DataColumnMapping(L"lastName", L"lastName")), (gcnew System::Data::Common::DataColumnMapping(L"firstName",

                           L"firstName")), (gcnew System::Data::Common::DataColumnMapping(L"phone", L"phone")), (gcnew System::Data::Common::DataColumnMapping(L"Expr1",

                           L"Expr1")), (gcnew System::Data::Common::DataColumnMapping(L"Expr2", L"Expr2")), (gcnew System::Data::Common::DataColumnMapping(L"Expr3",

                           L"Expr3")), (gcnew System::Data::Common::DataColumnMapping(L"Expr4", L"Expr4"))};

                     this->oleDbDataAdapter1->TableMappings->AddRange(gcnew cli::array< System::Data::Common::DataTableMapping^  >(1) {(gcnew System::Data::Common::DataTableMapping(L"Table",

                           L"Table1", __mcTemp__1))});

                     this->oleDbDataAdapter1->UpdateCommand = this->oleDbUpdateCommand1;

                     //

                     // Form1

                     //

                     this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);

                     this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

                     this->ClientSize = System::Drawing::Size(428, 320);

                     this->Controls->Add(this->label7);

                     this->Controls->Add(this->button4);

                     this->Controls->Add(this->label6);

                     this->Controls->Add(this->button3);

                     this->Controls->Add(this->label5);

                     this->Controls->Add(this->label4);

                     this->Controls->Add(this->button2);

                     this->Controls->Add(this->textBox4);

                     this->Controls->Add(this->button1);

                     this->Controls->Add(this->textBox3);

                     this->Controls->Add(this->label3);

                     this->Controls->Add(this->textBox2);

                     this->Controls->Add(this->label2);

                     this->Controls->Add(this->textBox1);

                     this->Controls->Add(this->label1);

                     this->Name = L"Form1";

                     this->Text = L"My Database Program";

                     this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

                     this->ResumeLayout(false);

                     this->PerformLayout();

 

              }

#pragma endregion

       private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)

                      {

                            oleDbConnection1->Open();                     

                      }

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)

               {

                         foundJustUsed=false;

                             try {

                   if ( !textBox1->Text->Equals( String::Empty ) &&

                          !textBox2->Text->Equals( String::Empty ) &&

                !textBox3->Text->Equals( String::Empty ) ) {

                // create the SQL query to insert a row                     

                           //********************

                 oleDbDataAdapter1->InsertCommand->CommandText =

                           "INSERT INTO `Table1` (`lastName`, `FirstName`, `Phone`) VALUES ('"+textBox2->Text+"', '"+ textBox1->Text+"', '"+textBox3->Text+"')" ;

                         //**********************

                textBox4->Text="\r\nSending query: "+oleDbDataAdapter1->InsertCommand->CommandText+"\r\n" ;

                // send query

                oleDbDataAdapter1->InsertCommand->ExecuteNonQuery();

                textBox4->Text="\r\nInsertion successful\r\n" ;

                } // end if

                else

                  MessageBox::Show("\r\nAll fields are required.\r\n") ;

               } // end try

               catch ( Exception ^Exception ) {

                  MessageBox::Show( Exception->Message, "Error, Person not inserted",

                     MessageBoxButtons::OK, MessageBoxIcon::Error );

               } // end catch

               }

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      String ^lastName="";

                      String ^firstName="";

                      foundJustUsed=true;

;

               

             firstName = textBox1->Text;

                      findFirst=firstName;                   

                   lastName=textBox2->Text;

                      findLast=lastName;

             try

                      {

                if ( !textBox1->Text->Equals( String::Empty ) &&

                         !textBox2->Text->Equals( String::Empty ) )

                           {

                             String ^myQuery = "SELECT Phone FROM Table1 WHERE firstName='"+textBox1->Text+"' AND lastName='"+textBox2->Text+"'";

                  OleDbCommand ^myCommand = gcnew OleDbCommand(myQuery, oleDbConnection1);

                             OleDbDataReader ^myReader; //works

                             myReader = myCommand->ExecuteReader();

                             myReader->Read();

                             textBox3->Text=myReader->GetString(0)->ToString();

                             myReader->Close();

                             textBox4->Text="\r\nSending query: SELECT Phone FROM Table1 WHERE firstName='"+textBox1->Text+"' AND lastName='"+textBox2->Text+"'";

                } // end if

                else

                  textBox4->Text="\r\nEnter First and Last Name required.\r\n" ;

               } // end try

               catch ( Exception ^Exception ) { //catches all errors

                  MessageBox::Show( Exception->Message, "Person not Found",

                     MessageBoxButtons::OK, MessageBoxIcon::Error );

               } // end catch

                        //***************************

               }

private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      String ^lastName="";

                      String ^firstName;

                      foundJustUsed=false;

               

             firstName = textBox1->Text;

                   lastName=textBox2->Text;

             try

                      {

                if ( !textBox1->Text->Equals( String::Empty ) &&

                         !textBox2->Text->Equals( String::Empty ) )

                           {

                             String ^myDelete = "Delete FROM Table1 WHERE firstName='"+textBox1->Text+"' AND lastName='"+textBox2->Text+"'";

                  OleDbCommand ^myCommand = gcnew OleDbCommand(myDelete, oleDbConnection1);

                             OleDbDataReader ^myReader; //works

                             myReader = myCommand->ExecuteReader();

                             myReader->Read();

                             myReader->Close();

                             textBox4->Text="\r\nSending Delete: Deleting FROM Table1 WHERE firstName='"+textBox1->Text+"' AND lastName='"+textBox2->Text+"'";

                             textBox1->Text="";

                             textBox2->Text="";

                             textBox3->Text="";

                } // end if

                else

                  textBox4->Text="\r\nEnter First and Last Name required.\r\n" ;

               } // end try

               catch ( Exception ^Exception ) {

                  MessageBox::Show( Exception->Message, "Error, Individual not deleted",

                     MessageBoxButtons::OK, MessageBoxIcon::Error );

               } // end catch

               }

private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      //a combination of delete then insert

                      String ^lastName="";

                      String ^firstName;

               

             firstName = textBox1->Text;

                   lastName=textBox2->Text;

                      if ( textBox1->Text->Equals( String::Empty ) ||

                            textBox2->Text->Equals( String::Empty ) || textBox3->Text->Equals( String::Empty ) || foundJustUsed==false )

                      {

                            textBox4->Text="\r\nError: Do a Find then Enter First,Last, and Phone.\r\n" ;

                      return;

                      }

 

             try

                      {               

                             String ^myDelete = "Delete FROM Table1 WHERE firstName='"+findFirst+"' AND lastName='"+findLast+"'";

                  OleDbCommand ^myCommand = gcnew OleDbCommand(myDelete, oleDbConnection1);

                             OleDbDataReader ^myReader; //works

                             myReader = myCommand->ExecuteReader();

                             myReader->Read();

                             myReader->Close();

                 } // end try

               catch ( Exception ^Exception ) {

                  MessageBox::Show( Exception->Message, "Error, entry not updated",

                     MessageBoxButtons::OK, MessageBoxIcon::Error );

                             return;

               } // end catch

                        //**********************************

                        //insert

                         try {

                        oleDbDataAdapter1->InsertCommand->CommandText =

                           "INSERT INTO `Table1` (`lastName`, `firstName`, `Phone`) VALUES ('"+textBox2->Text+"', '"+ textBox1->Text+"', '"+textBox3->Text+"')" ;

                         //**********************

                textBox4->Text="\r\nSending query: "+oleDbDataAdapter1->InsertCommand->CommandText+"\r\n" ;

                // send query

                oleDbDataAdapter1->InsertCommand->ExecuteNonQuery();

                textBox4->Text="\r\nInsertion successful\r\n" ;               

               } // end try

               catch ( OleDbException ^oleException ) {

                  MessageBox::Show( oleException->Message, "Error",

                     MessageBoxButtons::OK, MessageBoxIcon::Error );

               } // end catch

               }

};

}

 

     The program looks as follows when it runs:

(Back)


Tutorial 11 : Visual AddressBook using XML, Visual C++.NET 2008 and Access 2007 (Updated 12/11/2011)

Click here for the source code to the Visual AddressBook using XML in Visual C++.NET for the 2008. This program will involve using XML to talk to the database, written by Visual Basic using the Data Sources Tool which is no longer available in Visual C++.NET 2010 (but hopefully will be again in the future.) Hence it is impossible to make this program in the 2010 MSVC++.NET environment (and probably future MSVC versions). Open Microsoft Access (if you do not have Access 2007 use Access 2005, or a supplied database) and select new blank database. You can download a free redistributable version of Access at http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=10910   You may also need the Access database engine at http://www.microsoft.com/downloads/en/details.aspx?displaylang=en&FamilyID=c06b8369-60dd-4b64-a44b-84b371ede16d . You may not be able to directly make tables with what is provided in the links, but you will be able to access my database in the sample project. Depending on what version of Windows you have you may have to make some adjustments. There is an issue with 64 bit vs. 32 bit Windows7 (refer to http://support.microsoft.com/kb/942976) which says if you use a 64 bit operating system you must have a 32 bit datasource (database). The code here works in the 32 bit environment. If you wish to go to the 64 bit environment, it has been reported that if you use an older mdb database that you may be able to overcome this issue. Both PhoneBook.accdb written in Access 2010 format and PhoneBook.mdb written in a 2003 format are included in this project as well as all the graphics.

Create a directory called download on your c: drive in the root and save the file as PhoneBook.accdb

To create fields in access for the first name and last name be careful. If you choose a key word in Access the program won't. Specifically it turns out first and last have become key words. For a list of key words that you can't use as column names refer to http://sqlserver2000.databases.aspfaq.com/what-are-reserved-access-odbc-and-sql-server-keywords.html . So make the columns LastName, FirstName, Phone, and fill in as follows:

 

Try to exit Acess after you have entered your data and it will present the following, save this as is as Table1

Alternative:  Save the program as a 2005 mdb database:

This should look as follows:

 When you finish entering your data go to file and save the table as Table1 (the default).  Say yes to creating a primary field.  Since it matters where you put your database, it is easiest to put it in the root of your C:\ drive after you have created it.  Also be careful, databases may be case sensitive.  Close Access and your database before going on!

 Start a project in Visual C++ Studio 2008 as a C++ windows form application called AddressBook. Go the ToolBox and right click on the toolbar.  Select Choose items. 

 

From “Choose Toolbox Items” select Select OleDbDataAdapter and click OK.  This will take you back to the form and add the OleDbDataAdapter tool to the toolbox.

Right click on the toolbar.  Select add new items.  Select OleDbDataAdapter.  Draw the OleDbDataAdapter on the form.  In the window that appears select New Connection.

Select Change.

Select Microsoft Access Database File

Click Browse and browse to the AddressBook.mdb database on the root drive and then select OK.

Say Next

Say Next

Click Query Builder

Click Add and then Close

Select ID, LastName, FirstName and Phone and click OK.  Test by clicking execute Query. Then click OK

Click advanced Options

Click OK

Click Finish.

Below your form click  on the oleDbAdapter1 tool and an arrow will appear on its top.  Click on this arrow as shown below and select Generate DataSet.

Select OK in the next Window.

 Click Data on the Form, and select Show Data Sources

Expand Table 1 in the Data Sources Window as shown below.

Drag and Drop the LastName, FirstName, and Phone Tags to your form from the Data Sources Window.  When you do this labeled TextBoxes will appear on your form corresponding to the tags in the data sources window.

Add a data grid view and click on the arrow on the top right corner and select choose data source

Select Table1BindingSource

After the addition of the data grid view and making a link with the Table1BindingSource the form should look as follows:

Add the following buttons, groupbox, labels, textboxes and a picturebox with its sizemode set to stretch and open a default no image (saved as "Default.jpg") into the picturebox. To add pictures to your project add jpg's saved as a person's first name+last name+".jpg". You are welcome to use my default.jpg or create your own.

Insert the following code:

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)

               {

                      oleDbDataAdapter1->Fill(this->dataSet11->Table1);

             loadPicture();

               }

 

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)

                      {

                            this->Table1BindingSource ->MoveFirst() ;

                 loadPicture();          

             }

 

 

         void loadPicture()

      {

            String ^FirstN="";

            String ^LastN="";

            String ^filename="";

            FirstN=FirstNameTextBox->Text;           

            LastN=LastNameTextBox->Text;

            filename=FirstN+LastN+".jpg";

            try{

                 pictureBox1->Image=Image::FromFile(filename);

             }

             catch(Exception ^e)

             {

                 pictureBox1->Image=Image::FromFile("default.jpg");

 

             }

      }

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      this->Table1BindingSource ->MoveNext();

                      loadPicture();  

               }

private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e)

               {

                       this->Table1BindingSource ->MoveLast();

                       loadPicture();  

               }

private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      this->Table1BindingSource ->AddNew();

               }

private: System::Void button5_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      this->Validate();

             this->Table1BindingSource->EndEdit ();

             this->oleDbDataAdapter1->Update(this->dataSet11->Table1);

               }

private: System::Void button6_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      this->Table1BindingSource->RemoveCurrent();

               }

private: System::Void button7_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      this->Table1BindingSource->CancelEdit();

               }

private: System::Void button8_Click(System::Object^  sender, System::EventArgs^  e)

               {

                   String ^first=textBox1->Text;

                   String ^last=TextBox2->Text;

                   String ^phone="";

                   try

                   {

                     if (!textBox1->Text->Equals("") && !textBox2->Text->Equals(""))

                     {

                       this->Table1BindingSource->Filter="LastName='"+textBox2->Text+"' AND "+"FirstName='"+textBox1->Text+"'";

                     }

                     else if (!textBox2->Text->Equals("") )

                     {

                       this->Table1BindingSource->Filter="FirstName='"+textBox1->Text+"'";

                     }

                     else if (!textBox2->Text->Equals("") )

                     {

                       this->Table1BindingSource->Filter="LastName='"+textBox2->Text+"'";

                     }

                     else

                     {}

                   }

                   catch(Exception ^e)

                   {

                        pictureBox1->Image=Image::FromFile("default.jpg");

                   }

                   textBox3->Text=PhoneTextBox->Text; //loads the phone number

                   if (textBox3->Text->Equals(""))

                         textBox3->Text="Not Found";

                   loadPicture();

            

               }

private: System::Void button9_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      this->Table1BindingSource->RemoveFilter();

             this->Table1BindingSource->CancelEdit();

             loadPicture();        

               }

The final program should look as follows:

This is the way the program works:

1.  First Item, Next Record and Last Record allow you to navigate through the records. 

2. If you wish to add a record you must click Add Item.  Then enter in the last, first and phone fields to the left the information.  Then click Save Database.

3.  To find someone in the database, you must enter their first and last name in the find groupbox to the right.  Then click the Find Record button.

4.  If you wish to delete a record, first find them.  Then click Delete Record.  Then click Save Database.

5.  If you wish to see all the records again after a find, click Reset Record.

6.  Cancel is for canceling an Add Record or a Delete Record, before you hit save.

7.  To update a record either navigate to the person's record or do a Find Record. Then on the left edit first, last, or phone. Then click the Save Database button. To view this record and the rest click Reset Record.

 (Back) 


Tutorial 12: SQL Calls to a MySQL Database in Visual C++.NET 2010, 2008 (Updated 12/11/11)

1.  Download the MySQL database server/client: at http://www.mysql.com and select mysql community server>mysqlcommunity server>windows>windowsx86 zip/setup>pick a mirror>new user>No thanks just take me to the downloads>mysql-5.0.41-win32.zip.

Then install the executable by selecting custom. In the second window (as shown below) select that developer components should be installed to your hard drive, but go with the defaults on everything else. To download the VC.NET 2010 verion of the MySQL Database Project click here or for the 2008 version click here.

 

 MySQL Setup Wizard 

 

Then select skip sign-up.  Go with Detailed configuration.>Developer Machine>Multifunctional Database>C:  Installation Path>Decision Support (DSS)/OLAP>Enable TCP/IP Networking>Standard Character Set>Install as Windows Service and Include Bin Directory in Windows Path >Modify Security Settings (just done within MySQL…not as settings on your computer)  and type a root password (don’t forget this…or you will have to reinstall it. Here I set the password to "student") >Enable root access from remote machines>Execute

 

2.  Download the MySQL ODBC driver (open database connectivity)at database products>MySQL drivers>ODBC Driver for MySQL >Download>windows>windows x86 zip/setup.   Install as follows by first clicking Next as shown below:

Next Select Typical as shown below and click next:

Then click install as shown below:

Here I am using MySQL Connector/ODBC 3.51.

 

3.  Create Database and Tables by going to Start>All Programs>MySQL>MySQL Server 5.0 >MySQL command line client>(you are now at a command line)  type the password (I used "student") entered and hit enter> 

Then enter the following given in yellow:

 

Enter password: **********

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 2 to server version: 5.0.17-nt 

Type 'help;' or '\h' for help. Type '\c' to clear the buffer. 

mysql> create database mysampledatabase;

Query OK, 1 row affected (0.00 sec) 

mysql> use mysampledatabase;

Database changed

mysql> create table nameExample(first VARCHAR(255),last VARCHAR(255));

Query OK, 0 rows affected (0.06 sec) 

mysql> insert into nameExample(first,last) values ('Jim','Krumm');

Query OK, 1 row affected (0.03 sec) 

mysql> insert into nameExample(first,last) values ('Bob','Villa');

Query OK, 1 row affected (0.03 sec) 

mysql> insert into nameExample(first,last) values ('George',' Washington ');

Query OK, 1 row affected (0.03 sec) 

mysql> select * from nameExample;

+--------+------------+

| first  | last       |

+--------+------------+

| Jim    | Krumm      |

| Bob    | Villa      |

| George | Washington |

+--------+------------+

3 rows in set (0.00 sec) 

mysql>exit

 

It is important to note that a single database file has not been created (unlike Access), rather it is put in a collection of database files usually in a common set of  files. Also in MySQL it is appropriate to name columns first and last if you wish.

 

4.  Making a Program in Visual C++.NET 2010:

 

A.  Go to New Project>Visual C++>Windows Form Application: Name the programi MyMySQLVCProgram.

 

B.  Make the following form:

The Form's setup

 

  C.  Enter the following code to the form : This program does not use any of the built in database tools in the toolbox for Microsoft Visual C++.NET. It makes the link to the database from scratch. When running the program, hit the open connection button before executing any of the other buttons, and close the connection when finished. Particularly make sure the code highlighted in yellow is included. 

#pragma once

#include <iostream>

using namespace std;

 

namespace MyMySQLVCProgram {

 

        using namespace System;

        using namespace System::ComponentModel;

        using namespace System::Collections;

        using namespace System::Windows::Forms;

        using namespace System::Data;

        using namespace System::Drawing;

        using namespace Odbc;

 

        /// <summary>

        /// Summary for Form1

        /// </summary>

        public ref class Form1 : public System::Windows::Forms::Form

        {

        public:

                OdbcConnection ^myConnection;

                Form1(void)

                {

                        InitializeComponent();

                        //

                        //TODO: Add the constructor code here

                        //

                }

 

        protected:

                /// <summary>

                /// Clean up any resources being used.

                /// </summary>

                ~Form1()

                {

                        if (components)

                        {

                                delete components;

                        }

                }

        private: System::Windows::Forms::TextBox^  textBox6;

        protected:

        internal: System::Windows::Forms::Button^  Button1;

        private:

        private: System::Windows::Forms::Label^  label6;

        internal:

        private: System::Windows::Forms::GroupBox^  groupBox3;

        private: System::Windows::Forms::TextBox^  textBox5;

        private: System::Windows::Forms::Label^  label5;

        private: System::Windows::Forms::TextBox^  textBox4;

        internal: System::Windows::Forms::Button^  Button6;

        private:

        private: System::Windows::Forms::TextBox^  textBox3;

        internal:

        private: System::Windows::Forms::Label^  label4;

        private: System::Windows::Forms::Label^  label3;

        internal: System::Windows::Forms::Button^  Button8;

        private:

        private: System::Windows::Forms::GroupBox^  groupBox2;

        internal:

        private: System::Windows::Forms::TextBox^  textBox2;

        private: System::Windows::Forms::TextBox^  textBox1;

        private: System::Windows::Forms::Label^  label2;

        internal: System::Windows::Forms::Button^  Button7;

        private:

        private: System::Windows::Forms::Label^  label1;

        internal:

        internal: System::Windows::Forms::Button^  Button4;

        private:

        internal: System::Windows::Forms::Button^  Button5;

        internal: System::Windows::Forms::Button^  Button9;

        internal: System::Windows::Forms::GroupBox^  GroupBox1;

        internal: System::Windows::Forms::Button^  Button3;

        internal: System::Windows::Forms::Button^  Button2;

        internal: System::Windows::Forms::ListBox^  lstRecords;

 

        private:

                /// <summary>

                /// Required designer variable.

                /// </summary>

                System::ComponentModel::Container ^components;

 

#pragma region Windows Form Designer generated code

                /// <summary>

                /// Required method for Designer support - do not modify

                /// the contents of this method with the code editor.

                /// </summary>

                void InitializeComponent(void)

                {

                        this->textBox6 = (gcnew System::Windows::Forms::TextBox());

                        this->Button1 = (gcnew System::Windows::Forms::Button());

                        this->label6 = (gcnew System::Windows::Forms::Label());

                        this->groupBox3 = (gcnew System::Windows::Forms::GroupBox());

                        this->textBox5 = (gcnew System::Windows::Forms::TextBox());

                        this->label5 = (gcnew System::Windows::Forms::Label());

                        this->textBox4 = (gcnew System::Windows::Forms::TextBox());

                        this->Button6 = (gcnew System::Windows::Forms::Button());

                        this->textBox3 = (gcnew System::Windows::Forms::TextBox());

                        this->label4 = (gcnew System::Windows::Forms::Label());

                        this->label3 = (gcnew System::Windows::Forms::Label());

                        this->Button8 = (gcnew System::Windows::Forms::Button());

                        this->groupBox2 = (gcnew System::Windows::Forms::GroupBox());

                        this->textBox2 = (gcnew System::Windows::Forms::TextBox());

                        this->textBox1 = (gcnew System::Windows::Forms::TextBox());

                        this->label2 = (gcnew System::Windows::Forms::Label());

                        this->Button7 = (gcnew System::Windows::Forms::Button());

                        this->label1 = (gcnew System::Windows::Forms::Label());

                        this->Button4 = (gcnew System::Windows::Forms::Button());

                        this->Button5 = (gcnew System::Windows::Forms::Button());

                        this->Button9 = (gcnew System::Windows::Forms::Button());

                        this->GroupBox1 = (gcnew System::Windows::Forms::GroupBox());

                        this->Button3 = (gcnew System::Windows::Forms::Button());

                        this->Button2 = (gcnew System::Windows::Forms::Button());

                        this->lstRecords = (gcnew System::Windows::Forms::ListBox());

                        this->groupBox3->SuspendLayout();

                        this->groupBox2->SuspendLayout();

                        this->GroupBox1->SuspendLayout();

                        this->SuspendLayout();

                        //

                        // textBox6

                        //

                        this->textBox6->Location = System::Drawing::Point(27, 172);

                        this->textBox6->Name = L"textBox6";

                        this->textBox6->Size = System::Drawing::Size(65, 20);

                        this->textBox6->TabIndex = 8;

                        //

                        // Button1

                        //

                        this->Button1->Location = System::Drawing::Point(15, 36);

                        this->Button1->Name = L"Button1";

                        this->Button1->Size = System::Drawing::Size(146, 29);

                        this->Button1->TabIndex = 11;

                        this->Button1->Text = L"Open Connection";

                        this->Button1->UseVisualStyleBackColor = true;

                        this->Button1->Click += gcnew System::EventHandler(this, &Form1::Button1_Click);

                        //

                        // label6

                        //

                        this->label6->AutoSize = true;

                        this->label6->Location = System::Drawing::Point(23, 153);

                        this->label6->Name = L"label6";

                        this->label6->Size = System::Drawing::Size(70, 13);

                        this->label6->TabIndex = 12;

                        this->label6->Text = L"Modified Last";

                        //

                        // groupBox3

                        //

                        this->groupBox3->Controls->Add(this->textBox6);

                        this->groupBox3->Controls->Add(this->label6);

                        this->groupBox3->Controls->Add(this->textBox5);

                        this->groupBox3->Controls->Add(this->label5);

                        this->groupBox3->Controls->Add(this->textBox4);

                        this->groupBox3->Controls->Add(this->Button6);

                        this->groupBox3->Controls->Add(this->textBox3);

                        this->groupBox3->Controls->Add(this->label4);

                        this->groupBox3->Controls->Add(this->label3);

                        this->groupBox3->Location = System::Drawing::Point(570, 36);

                        this->groupBox3->Name = L"groupBox3";

                        this->groupBox3->Size = System::Drawing::Size(120, 243);

                        this->groupBox3->TabIndex = 15;

                        this->groupBox3->TabStop = false;

                        this->groupBox3->Text = L"Modify";

                        //

                        // textBox5

                        //

                        this->textBox5->Location = System::Drawing::Point(26, 125);

                        this->textBox5->Name = L"textBox5";

                        this->textBox5->Size = System::Drawing::Size(65, 20);

                        this->textBox5->TabIndex = 11;

                        //

                        // label5

                        //

                        this->label5->AutoSize = true;

                        this->label5->Location = System::Drawing::Point(23, 107);

                        this->label5->Name = L"label5";

                        this->label5->Size = System::Drawing::Size(69, 13);

                        this->label5->TabIndex = 10;

                        this->label5->Text = L"Modified First";

                        //

                        // textBox4

                        //

                        this->textBox4->Location = System::Drawing::Point(27, 75);

                        this->textBox4->Name = L"textBox4";

                        this->textBox4->Size = System::Drawing::Size(65, 20);

                        this->textBox4->TabIndex = 9;

                        //

                        // Button6

                        //

                        this->Button6->Location = System::Drawing::Point(6, 198);

                        this->Button6->Name = L"Button6";

                        this->Button6->Size = System::Drawing::Size(104, 31);

                        this->Button6->TabIndex = 5;

                        this->Button6->Text = L"Find and Modify";

                        this->Button6->UseVisualStyleBackColor = true;

                        this->Button6->Click += gcnew System::EventHandler(this, &Form1::Button6_Click);

                        //

                        // textBox3

                        //

                        this->textBox3->Location = System::Drawing::Point(27, 37);

                        this->textBox3->Name = L"textBox3";

                        this->textBox3->Size = System::Drawing::Size(65, 20);

                        this->textBox3->TabIndex = 8;

                        //

                        // label4

                        //

                        this->label4->AutoSize = true;

                        this->label4->Location = System::Drawing::Point(42, 60);

                        this->label4->Name = L"label4";

                        this->label4->Size = System::Drawing::Size(23, 13);

                        this->label4->TabIndex = 7;

                        this->label4->Text = L"last";

                        //

                        // label3

                        //

                        this->label3->AutoSize = true;

                        this->label3->Location = System::Drawing::Point(42, 20);

                        this->label3->Name = L"label3";

                        this->label3->Size = System::Drawing::Size(23, 13);

                        this->label3->TabIndex = 6;

                        this->label3->Text = L"first";

                        //

                        // Button8

                        //

                        this->Button8->Location = System::Drawing::Point(15, 181);

                        this->Button8->Name = L"Button8";

                        this->Button8->Size = System::Drawing::Size(146, 31);

                        this->Button8->TabIndex = 7;

                        this->Button8->Text = L"List Sorted by First and Last";

                        this->Button8->UseVisualStyleBackColor = true;

                        this->Button8->Click += gcnew System::EventHandler(this, &Form1::Button8_Click);

                        //

                        // groupBox2

                        //

                        this->groupBox2->Controls->Add(this->textBox2);

                        this->groupBox2->Controls->Add(this->textBox1);

                        this->groupBox2->Controls->Add(this->label2);

                        this->groupBox2->Controls->Add(this->Button7);

                        this->groupBox2->Controls->Add(this->label1);

                        this->groupBox2->Controls->Add(this->Button4);

                        this->groupBox2->Controls->Add(this->Button5);

                        this->groupBox2->Location = System::Drawing::Point(182, 131);

                        this->groupBox2->Name = L"groupBox2";

                        this->groupBox2->Size = System::Drawing::Size(343, 142);

                        this->groupBox2->TabIndex = 8;

                        this->groupBox2->TabStop = false;

                        this->groupBox2->Text = L"Enter First Last Names";

                        //

                        // textBox2

                        //

                        this->textBox2->Location = System::Drawing::Point(163, 37);

                        this->textBox2->Name = L"textBox2";

                        this->textBox2->Size = System::Drawing::Size(65, 20);

                        this->textBox2->TabIndex = 7;

                        //

                        // textBox1

                        //

                        this->textBox1->Location = System::Drawing::Point(79, 36);

                        this->textBox1->Name = L"textBox1";

                        this->textBox1->Size = System::Drawing::Size(65, 20);

                        this->textBox1->TabIndex = 6;

                        //

                        // label2

                        //

                        this->label2->AutoSize = true;

                        this->label2->Location = System::Drawing::Point(102, 20);

                        this->label2->Name = L"label2";

                        this->label2->Size = System::Drawing::Size(23, 13);

                        this->label2->TabIndex = 5;

                        this->label2->Text = L"first";

                        //

                        // Button7

                        //

                        this->Button7->Location = System::Drawing::Point(168, 67);

                        this->Button7->Name = L"Button7";

                        this->Button7->Size = System::Drawing::Size(146, 26);

                        this->Button7->TabIndex = 6;

                        this->Button7->Text = L"Delete";

                        this->Button7->UseVisualStyleBackColor = true;

                        this->Button7->Click += gcnew System::EventHandler(this, &Form1::Button7_Click);

                        //

                        // label1

                        //

                        this->label1->AutoSize = true;

                        this->label1->Location = System::Drawing::Point(185, 21);

                        this->label1->Name = L"label1";

                        this->label1->Size = System::Drawing::Size(23, 13);

                        this->label1->TabIndex = 4;

                        this->label1->Text = L"last";

                        //

                        // Button4

                        //

                        this->Button4->Location = System::Drawing::Point(16, 62);

                        this->Button4->Name = L"Button4";

                        this->Button4->Size = System::Drawing::Size(146, 31);

                        this->Button4->TabIndex = 3;

                        this->Button4->Text = L"Find WildCard Partial Match";

                        this->Button4->UseVisualStyleBackColor = true;

                        this->Button4->Click += gcnew System::EventHandler(this, &Form1::Button4_Click);

                        //

                        // Button5

                        //

                        this->Button5->Location = System::Drawing::Point(84, 109);

                        this->Button5->Name = L"Button5";

                        this->Button5->Size = System::Drawing::Size(146, 27);

                        this->Button5->TabIndex = 4;

                        this->Button5->Text = L"Insert";

                        this->Button5->UseVisualStyleBackColor = true;

                        this->Button5->Click += gcnew System::EventHandler(this, &Form1::Button5_Click);

                        //

                        // Button9

                        //

                        this->Button9->Location = System::Drawing::Point(15, 231);

                        this->Button9->Name = L"Button9";

                        this->Button9->Size = System::Drawing::Size(146, 31);

                        this->Button9->TabIndex = 13;

                        this->Button9->Text = L"Close Connection";

                        this->Button9->UseVisualStyleBackColor = true;

                        this->Button9->Click += gcnew System::EventHandler(this, &Form1::Button9_Click);

                        //

                        // GroupBox1

                        //

                        this->GroupBox1->Controls->Add(this->groupBox2);

                        this->GroupBox1->Controls->Add(this->Button1);

                        this->GroupBox1->Controls->Add(this->Button8);

                        this->GroupBox1->Controls->Add(this->Button9);

                        this->GroupBox1->Controls->Add(this->Button3);

                        this->GroupBox1->Controls->Add(this->Button2);

                        this->GroupBox1->Controls->Add(this->lstRecords);

                        this->GroupBox1->Location = System::Drawing::Point(21, 17);

                        this->GroupBox1->Name = L"GroupBox1";

                        this->GroupBox1->Size = System::Drawing::Size(531, 292);

                        this->GroupBox1->TabIndex = 14;

                        this->GroupBox1->TabStop = false;

                        this->GroupBox1->Text = L"Stuff to Do";

                        this->GroupBox1->Enter += gcnew System::EventHandler(this, &Form1::GroupBox1_Enter);

                        //

                        // Button3

                        //

                        this->Button3->Location = System::Drawing::Point(12, 134);

                        this->Button3->Name = L"Button3";

                        this->Button3->Size = System::Drawing::Size(149, 31);

                        this->Button3->TabIndex = 2;

                        this->Button3->Text = L"List The Records";

                        this->Button3->UseVisualStyleBackColor = true;

                        this->Button3->Click += gcnew System::EventHandler(this, &Form1::Button3_Click);

                        //

                        // Button2

                        //

                        this->Button2->Location = System::Drawing::Point(15, 85);

                        this->Button2->Name = L"Button2";

                        this->Button2->Size = System::Drawing::Size(144, 29);

                        this->Button2->TabIndex = 1;

                        this->Button2->Text = L"Get Number of Records";

                        this->Button2->UseVisualStyleBackColor = true;

                        this->Button2->Click += gcnew System::EventHandler(this, &Form1::Button2_Click);

                        //

                        // lstRecords

                        //

                        this->lstRecords->FormattingEnabled = true;

                        this->lstRecords->Location = System::Drawing::Point(266, 19);

                        this->lstRecords->Name = L"lstRecords";

                        this->lstRecords->Size = System::Drawing::Size(247, 95);

                        this->lstRecords->TabIndex = 0;

                        //

                        // Form1

                        //

                        this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);

                        this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

                        this->ClientSize = System::Drawing::Size(710, 326);

                        this->Controls->Add(this->groupBox3);

                        this->Controls->Add(this->GroupBox1);

                        this->Name = L"Form1";

                        this->Text = L"VC.NET MySQL Database Program";

                        this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

                        this->groupBox3->ResumeLayout(false);

                        this->groupBox3->PerformLayout();

                        this->groupBox2->ResumeLayout(false);

                        this->groupBox2->PerformLayout();

                        this->GroupBox1->ResumeLayout(false);

                        this->ResumeLayout(false);

 

                }

#pragma endregion

        private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

                         }

private: System::Void Button1_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //Open Connection button

                          if(myConnection==nullptr)

                                  {

                                          myConnection= gcnew OdbcConnection;

                                  }

                         

                         if(myConnection->State==ConnectionState::Open)

                                  {

                                          myConnection->Close();

                                  }                            

                                  String  ^connectionstring="";

                                  String ^username="root";

                                  String ^password="student";

                                  String ^server="localhost";

                                  String ^driver="{MySQL ODBC 3.51 Driver}";

                                  String ^database = "mysampledatabase";

                                  connectionstring = "Driver=" + driver + "; Server=" + server + "; User=" + username + "; Password=" + password + ";Database=" + database + ";";

                                  myConnection->ConnectionString = connectionstring;

                                  try

                                  {

                      myConnection->Open();

                                  }

                  catch (Exception ^e)

                                  {

                                          MessageBox::Show(e->ToString());

                                  }

                                  if (myConnection->State!=ConnectionState::Open)

                                   {

                                           MessageBox::Show("Error Opening Connection");

                                   }

                                  else if(myConnection->State==ConnectionState::Open)

                                          MessageBox::Show("Connection opened!");

                 }

private: System::Void Button2_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //Get Number of Records button

                         if(myConnection->State!=ConnectionState::Open)

                          {

                                  MessageBox::Show("error");

                                return;

                          }

              OdbcCommand ^sqlCommand=gcnew OdbcCommand;

                          sqlCommand->Connection=myConnection;

              sqlCommand->CommandText= "select count(*) as RecordCount from nameExample";

                          String ^result=sqlCommand->ExecuteScalar()->ToString();

                          MessageBox::Show(result);

                 }

private: System::Void Button3_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //List Records button

                         String ^temp="";

                    if(myConnection->State!=ConnectionState::Open)

                        {

                                MessageBox::Show("Connection is not open");

                                return;

                        }

                        OdbcCommand ^sqlCommand=gcnew OdbcCommand;

                        OdbcDataReader ^result;

                        sqlCommand->Connection=myConnection;

                        sqlCommand->CommandText = "select * from nameExample";

                        result = sqlCommand->ExecuteReader();

                        lstRecords->Items->Clear();

                        while (result->Read())

                        {

                                lstRecords->Items->Add(result->GetValue(0)->ToString() + ", " + result->GetValue(1)->ToString());

                        }

                       

                        result=nullptr;

                        sqlCommand=nullptr;

                 }

private: System::Void Button4_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //Find Wildcard Match button

                         lstRecords->Items->Clear();

                         String ^lastname="";

                         String ^firstname="";

                         if(textBox1->Text=="" && textBox2->Text=="")

                         {

                                 MessageBox::Show("Enter First or Last or First and Last Name");

                                 return;

                         }

                         firstname=textBox1->Text;

                         lastname=textBox2->Text;

             String ^sqlFind="";

                         OdbcCommand ^sqlCommand=gcnew OdbcCommand;

                         OdbcDataReader ^result;

                         int found=-1;

                         sqlFind = "select * from nameExample Where last like '%" + lastname + "%' and first like '%" + firstname + "%'";

                         sqlCommand->Connection=myConnection;

                         sqlCommand->CommandText = sqlFind;

                         result = sqlCommand->ExecuteReader();

                         

             found = 0;

                         while(result->Read())

                         {

                lstRecords->Items->Add(result->GetValue(0)->ToString() + " " + result->GetValue(1)->ToString());

                found = found + 1;

                         }

                         MessageBox::Show(found + " record(s) found!");

                         result=nullptr;

                         sqlCommand=nullptr;

                 }

private: System::Void Button5_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //Insert button

                         lstRecords->Items->Clear();

                         String ^lastname="";

                         String ^firstname="";

                         

                         if(textBox1->Text=="" || textBox2->Text=="")

                         {

                                 MessageBox::Show("Both First and Last Name Required!");

                                 return;

                         }

                         firstname=textBox1->Text;

                         lastname=textBox2->Text;

             String ^sqlInsert="";

                         

                         OdbcCommand ^sqlCommand=gcnew OdbcCommand;

                         int  result=-1;

                          sqlInsert = "insert into nameExample(first, last) values ('" + firstname + "', '" + lastname + "')";

                          sqlCommand->Connection = myConnection;

                         sqlCommand->CommandText = sqlInsert;

                         

                         result = sqlCommand->ExecuteNonQuery();

 

                         if(result==0)

                         {

                                 MessageBox::Show("No records inserted!");

                         }

                         else

                         {

                                 MessageBox::Show(result + " record inserted!");

                         }

                         result=-1;

                         sqlCommand=nullptr;

                 }

private: System::Void Button6_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //Find and Modify button

                         String ^firstname;

                         String ^lastname;

                         String ^newfirstname;

                         String ^newlastname;

                         if(textBox3->Text=="" && textBox4->Text == "" && textBox5->Text=="" && textBox6->Text=="")

                         {

                                 MessageBox::Show("Enter target first and last names, and modified first and last names!");

                                 return;

                         }

                         firstname=textBox3->Text;

                         lastname=textBox4->Text;      

                         newfirstname=textBox5->Text;

                         newlastname=textBox6->Text;

                         String ^sqlFind;

                         String ^sqlUpdate;

                         OdbcCommand ^sqlCommand=gcnew OdbcCommand;

                         OdbcCommand ^sqlUpdateCommand=gcnew OdbcCommand;

                         OdbcDataReader ^result;

                         int updatecount;

             sqlFind = "select * from nameExample Where last = '" + lastname + "' and first = '" + firstname + "'";

             sqlCommand->Connection = myConnection;

                         sqlCommand->CommandText = sqlFind;

                         result = sqlCommand->ExecuteReader();

                         if(!result->HasRows)

                         {

                                 MessageBox::Show("No records found to modify");

                         }

                         else

                         {     

                                 result->Close();

                                 result=nullptr;

                                 sqlUpdate = "update nameExample set first = '" + newfirstname + "', last = '" + newlastname + "' where first = '" + firstname + "' and last = '" + lastname + "'";

                                 sqlUpdateCommand->Connection = myConnection;

                                 sqlUpdateCommand->CommandText = sqlUpdate;

                                 updatecount = sqlUpdateCommand->ExecuteNonQuery();

                                 if(updatecount==0)

                                 {

                                         MessageBox::Show("No records updated!");

                                 }

                                 else

                                 {

                                         MessageBox::Show("Record updated!");

                                 }

                         }

                         result=nullptr;

                         sqlUpdateCommand=nullptr;//();

                         sqlCommand=nullptr;

                 }

private: System::Void Button7_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //Delete button

                         String ^lastname;

                         String ^firstname;

                         firstname=textBox1->Text;

                         lastname=textBox2->Text;

                         String ^sqlDelete;

                         int result;

                         OdbcCommand ^sqlCommand=gcnew OdbcCommand;

                         sqlDelete = "delete from nameExample Where last = '" + lastname + "' and first = '" + firstname + "'";

             sqlCommand->Connection = myConnection;

                         sqlCommand->CommandText = sqlDelete;

                         result = sqlCommand->ExecuteNonQuery();

                         if (result==0)

                         {

                 MessageBox::Show("No records deleted!");

                         }

                         else

                         {

                 MessageBox::Show(result + " record(s) deleted!");

                         }

                         sqlCommand=nullptr;

                 }

private: System::Void Button8_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //List Sorted button

                         if( myConnection->State != ConnectionState::Open)

                         {

                                 return;

                         }

             OdbcCommand ^sqlCommand=gcnew OdbcCommand;

                         OdbcDataReader ^result;

                         sqlCommand->Connection = myConnection;

                         sqlCommand->CommandText = "select * from nameExample order by last, first";

             result = sqlCommand->ExecuteReader();

                         lstRecords->Items->Clear();

                         while(result->Read())

                         {

                                 lstRecords->Items->Add(result->GetValue(0)->ToString() + ", " + result->GetValue(1)->ToString());

                         }

                         sqlCommand=nullptr;

                 }

private: System::Void Button9_Click(System::Object^  sender, System::EventArgs^  e)

                 {

                         //Close Connection button

                         if(myConnection==nullptr)

                        {

                                MessageBox::Show("No Connection to close");

                                                  return;

                        }

 

                        if(myConnection->State!=ConnectionState::Open)

                        {

                                MessageBox::Show("Connection is not open");

                                return;

                        }

                        myConnection->Close();

                        if(myConnection->State==ConnectionState::Closed)

                        {

                                MessageBox::Show("Connection is closed");

                                return;

                        }

                 }

private: System::Void GroupBox1_Enter(System::Object^  sender, System::EventArgs^  e) {

                 }

};

}

To run the program:

1. Click Open Connecton before pressing any other button

2. Perform any of the operations on any of the other buttons.

3. To quit click Close Connection

This is what the program looks like when it runs:

  

  (Back) 

 


Tutorial 13: Creating a Visual C++ Project from Scratch in 2010 that Calls an Access Database in Visual C++.NET 2010 (No XML) (Updated 12/11/2011)

The Form:  Click here for a complete project with source in MSVC++.NET 2010. This program runs and compiles in 32 Bit Windows XP. The executable should run in Windows 7, 64 bit, provided the database is present, and the path adjusted to the database. But development can an issue because of the 32 bit vs. 64 bit drivers. I have a student who reports that using a older mdb database may resolve the issue with working on 64 Windows 7 using a 32 bit database, and then using the older Jet driver instead of ACE. At any rate, this program uses a database set inside it's innermost debug directory (which may have to be adjusted in Windows 7). A 2010 accdb database and a 2002 mdb database (with a working but remarked connection string) is included in the above zip files. If you run the 2002 mdb database and need the Microsoft jet driver refer to http://support.microsoft.com/kb/239114. This program does not use Odbcad32. However to make this work you will need to at least install the Access Runtime available as a free download from Microsoft. To download the Access Runtime go to http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=10910   

and/or the Microsoft Access Database Engine at:

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=13255

This is the best way to set up the project.  It does not rely on any special tools in MVC++.NET, and you form the link to the database right in your code.  The code works with 2008 and 20010.  Begin by creating a project called myPhoneBook and designing the form as shown below.  Note, by default the textboxes will start with a lower case (t)extBox, so you will need to rename these with an uppercase (T)extBox to use my code below:

Database and Pictures:  The way I have the database here it assumes your database is in the root of your C: drive.  If you have Windows 7 you may have to place the database in with your source files and adjust the path to your database in your source file accordingly.  Copy new pictures of people in the address book folder into the source file directory using the convention of firstname+lastname+”.jpg” .

Insert the Following Code:

#pragma once

#include <iostream> //needed for NULL

 

namespace mvcAccessScratchUsingOleDb {

 

       using namespace System;

       using namespace System::ComponentModel;

       using namespace System::Collections;

       using namespace System::Windows::Forms;

       using namespace System::Data;

       using namespace System::Drawing;

       //*********************************

       //add this

       using namespace System::Data::OleDb;

 

       /// <summary>

       /// Summary for Form1

       ///

       /// WARNING: If you change the name of this class, you will need to change the

       ///          'Resource File Name' property for the managed resource compiler tool

       ///          associated with all .resx files this class depends on.  Otherwise,

       ///          the designers will not be able to interact properly with localized

       ///          resources associated with this form.

       /// </summary>

       public ref class Form1 : public System::Windows::Forms::Form

       {

       public:

              static OleDbConnection ^myConnection=gcnew OleDbConnection;

              Form1(void)

              {

                    

                     InitializeComponent();

                     //using namespace System::Data::Sql;

                     //

                     //TODO: Add the constructor code here

                     //

              }

 

       protected:

              /// <summary>

              /// Clean up any resources being used.

              /// </summary>

              ~Form1()

              {

                     if (components)

                     {

                           delete components;

                     }

              }

       internal: System::Windows::Forms::GroupBox^  GroupBox1;

       protected:

       internal: System::Windows::Forms::Label^  label7;

       internal: System::Windows::Forms::Label^  Label1;

       internal: System::Windows::Forms::Label^  Label2;

       internal: System::Windows::Forms::TextBox^  TextBox2;

       internal: System::Windows::Forms::TextBox^  TextBox1;

       internal: System::Windows::Forms::TextBox^  TextBox3;

       internal: System::Windows::Forms::Button^  Button8;

       internal: System::Windows::Forms::Button^  Button9;

       internal: System::Windows::Forms::Button^  Button7;

       internal: System::Windows::Forms::Button^  Button6;

       internal: System::Windows::Forms::Button^  Button5;

       internal: System::Windows::Forms::Button^  Button4;

       internal: System::Windows::Forms::Button^  Button3;

       internal: System::Windows::Forms::Button^  Button2;

       internal: System::Windows::Forms::Button^  Button1;

       private: System::Windows::Forms::GroupBox^  groupBox2;

       internal:

       internal: System::Windows::Forms::Button^  Button10;

       private:

       internal: System::Windows::Forms::Label^  label9;

       internal: System::Windows::Forms::Label^  Label6;

       internal: System::Windows::Forms::Label^  Label5;

       internal: System::Windows::Forms::TextBox^  TextBox8;

       internal: System::Windows::Forms::TextBox^  TextBox7;

       internal: System::Windows::Forms::TextBox^  TextBox6;

       internal: System::Windows::Forms::Label^  Label4;

       internal: System::Windows::Forms::Label^  Label3;

       internal: System::Windows::Forms::TextBox^  TextBox5;

       internal: System::Windows::Forms::TextBox^  TextBox4;

       internal: System::Windows::Forms::ListBox^  ListBox1;

       private: System::Windows::Forms::PictureBox^  pictureBox1;

       internal:

 

       private:

              /// <summary>

              /// Required designer variable.

              /// </summary>

              System::ComponentModel::Container ^components;

 

#pragma region Windows Form Designer generated code

              /// <summary>

              /// Required method for Designer support - do not modify

              /// the contents of this method with the code editor.

              /// </summary>

              void InitializeComponent(void)

              {

                     System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));

                     this->GroupBox1 = (gcnew System::Windows::Forms::GroupBox());

                     this->label7 = (gcnew System::Windows::Forms::Label());

                     this->Label1 = (gcnew System::Windows::Forms::Label());

                     this->Label2 = (gcnew System::Windows::Forms::Label());

                     this->TextBox2 = (gcnew System::Windows::Forms::TextBox());

                     this->TextBox1 = (gcnew System::Windows::Forms::TextBox());

                     this->TextBox3 = (gcnew System::Windows::Forms::TextBox());

                     this->Button8 = (gcnew System::Windows::Forms::Button());

                     this->Button9 = (gcnew System::Windows::Forms::Button());

                     this->Button7 = (gcnew System::Windows::Forms::Button());

                     this->Button6 = (gcnew System::Windows::Forms::Button());

                     this->Button5 = (gcnew System::Windows::Forms::Button());

                     this->Button4 = (gcnew System::Windows::Forms::Button());

                     this->Button3 = (gcnew System::Windows::Forms::Button());

                     this->Button2 = (gcnew System::Windows::Forms::Button());

                     this->Button1 = (gcnew System::Windows::Forms::Button());

                     this->groupBox2 = (gcnew System::Windows::Forms::GroupBox());

                     this->Button10 = (gcnew System::Windows::Forms::Button());

                     this->label9 = (gcnew System::Windows::Forms::Label());

                     this->Label6 = (gcnew System::Windows::Forms::Label());

                     this->Label5 = (gcnew System::Windows::Forms::Label());

                     this->TextBox8 = (gcnew System::Windows::Forms::TextBox());

                     this->TextBox7 = (gcnew System::Windows::Forms::TextBox());

                     this->TextBox6 = (gcnew System::Windows::Forms::TextBox());

                     this->Label4 = (gcnew System::Windows::Forms::Label());

                     this->Label3 = (gcnew System::Windows::Forms::Label());

                     this->TextBox5 = (gcnew System::Windows::Forms::TextBox());

                     this->TextBox4 = (gcnew System::Windows::Forms::TextBox());

                     this->ListBox1 = (gcnew System::Windows::Forms::ListBox());

                     this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());

                     this->GroupBox1->SuspendLayout();

                     this->groupBox2->SuspendLayout();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->BeginInit();

                     this->SuspendLayout();

                     //

                     // GroupBox1

                     //

                     this->GroupBox1->Controls->Add(this->label7);

                     this->GroupBox1->Controls->Add(this->Label1);

                     this->GroupBox1->Controls->Add(this->Label2);

                     this->GroupBox1->Controls->Add(this->TextBox2);

                     this->GroupBox1->Controls->Add(this->TextBox1);

                     this->GroupBox1->Controls->Add(this->TextBox3);

                     this->GroupBox1->Location = System::Drawing::Point(12, 12);

                     this->GroupBox1->Name = L"GroupBox1";

                     this->GroupBox1->Size = System::Drawing::Size(141, 116);

                     this->GroupBox1->TabIndex = 38;

                     this->GroupBox1->TabStop = false;

                     this->GroupBox1->Text = L"Enter First Last Names";

                     //

                     // label7

                     //

                     this->label7->AutoSize = true;

                     this->label7->Location = System::Drawing::Point(3, 88);

                     this->label7->Name = L"label7";

                     this->label7->Size = System::Drawing::Size(38, 13);

                     this->label7->TabIndex = 13;

                     this->label7->Text = L"Phone";

                     //

                     // Label1

                     //

                     this->Label1->AutoSize = true;

                     this->Label1->Location = System::Drawing::Point(4, 27);

                     this->Label1->Name = L"Label1";

                     this->Label1->Size = System::Drawing::Size(26, 13);

                     this->Label1->TabIndex = 7;

                     this->Label1->Text = L"First";

                     //

                     // Label2

                     //

                     this->Label2->AutoSize = true;

                     this->Label2->Location = System::Drawing::Point(3, 60);

                     this->Label2->Name = L"Label2";

                     this->Label2->Size = System::Drawing::Size(27, 13);

                     this->Label2->TabIndex = 8;

                     this->Label2->Text = L"Last";

                     //

                     // TextBox2

                     //

                     this->TextBox2->Location = System::Drawing::Point(47, 57);

                     this->TextBox2->Name = L"TextBox2";

                     this->TextBox2->Size = System::Drawing::Size(78, 20);

                     this->TextBox2->TabIndex = 6;

                     //

                     // TextBox1

                     //

                     this->TextBox1->Location = System::Drawing::Point(47, 27);

                     this->TextBox1->Name = L"TextBox1";

                     this->TextBox1->Size = System::Drawing::Size(78, 20);

                     this->TextBox1->TabIndex = 5;

                     //

                     // TextBox3

                     //

                     this->TextBox3->Location = System::Drawing::Point(46, 88);

                     this->TextBox3->Name = L"TextBox3";

                     this->TextBox3->Size = System::Drawing::Size(79, 20);

                     this->TextBox3->TabIndex = 0;

                     //

                     // Button8

                     //

                     this->Button8->Location = System::Drawing::Point(177, 229);

                     this->Button8->Name = L"Button8";

                     this->Button8->Size = System::Drawing::Size(77, 56);

                     this->Button8->TabIndex = 39;

                     this->Button8->Text = L"Delete";

                     this->Button8->UseVisualStyleBackColor = true;

                     this->Button8->Click += gcnew System::EventHandler(this, &Form1::Button8_Click);

                     //

                     // Button9

                     //

                     this->Button9->Location = System::Drawing::Point(177, 289);

                     this->Button9->Name = L"Button9";

                     this->Button9->Size = System::Drawing::Size(77, 56);

                     this->Button9->TabIndex = 38;

                     this->Button9->Text = L"Insert";

                     this->Button9->UseVisualStyleBackColor = true;

                     this->Button9->Click += gcnew System::EventHandler(this, &Form1::Button9_Click);

                     //

                     // Button7

                     //

                     this->Button7->Location = System::Drawing::Point(176, 167);

                     this->Button7->Name = L"Button7";

                     this->Button7->Size = System::Drawing::Size(77, 56);

                     this->Button7->TabIndex = 37;

                     this->Button7->Text = L"Find Wild Card Partial Match";

                     this->Button7->UseVisualStyleBackColor = true;

                     this->Button7->Click += gcnew System::EventHandler(this, &Form1::Button7_Click);

                     //

                     // Button6

                     //

                     this->Button6->Location = System::Drawing::Point(94, 289);

                     this->Button6->Name = L"Button6";

                     this->Button6->Size = System::Drawing::Size(77, 56);

                     this->Button6->TabIndex = 44;

                     this->Button6->Text = L"Close Connection";

                     this->Button6->UseVisualStyleBackColor = true;

                     this->Button6->Click += gcnew System::EventHandler(this, &Form1::Button6_Click);

                     //

                     // Button5

                     //

                     this->Button5->Location = System::Drawing::Point(93, 229);

                     this->Button5->Name = L"Button5";

                     this->Button5->Size = System::Drawing::Size(77, 56);

                     this->Button5->TabIndex = 45;

                     this->Button5->Text = L"List Sorted by Last ";

                     this->Button5->UseVisualStyleBackColor = true;

                     this->Button5->Click += gcnew System::EventHandler(this, &Form1::Button5_Click);

                     //

                     // Button4

                     //

                     this->Button4->Location = System::Drawing::Point(94, 166);

                     this->Button4->Name = L"Button4";

                     this->Button4->Size = System::Drawing::Size(77, 56);

                     this->Button4->TabIndex = 43;

                     this->Button4->Text = L"List Sorted By First";

                     this->Button4->UseVisualStyleBackColor = true;

                     this->Button4->Click += gcnew System::EventHandler(this, &Form1::Button4_Click);

                     //

                     // Button3

                     //

                     this->Button3->Location = System::Drawing::Point(10, 291);

                     this->Button3->Name = L"Button3";

                     this->Button3->Size = System::Drawing::Size(77, 56);

                     this->Button3->TabIndex = 42;

                     this->Button3->Text = L"List Records";

                     this->Button3->UseVisualStyleBackColor = true;

                     this->Button3->Click += gcnew System::EventHandler(this, &Form1::Button3_Click);

                     //

                     // Button2

                     //

                     this->Button2->Location = System::Drawing::Point(11, 228);

                     this->Button2->Name = L"Button2";

                     this->Button2->Size = System::Drawing::Size(77, 56);

                     this->Button2->TabIndex = 41;

                     this->Button2->Text = L"Count Records";

                     this->Button2->UseVisualStyleBackColor = true;

                     this->Button2->Click += gcnew System::EventHandler(this, &Form1::Button2_Click);

                     //

                     // Button1

                     //

                     this->Button1->Location = System::Drawing::Point(11, 165);

                     this->Button1->Name = L"Button1";

                     this->Button1->Size = System::Drawing::Size(77, 56);

                     this->Button1->TabIndex = 40;

                     this->Button1->Text = L"Make Connection";

                     this->Button1->UseVisualStyleBackColor = true;

                     this->Button1->Click += gcnew System::EventHandler(this, &Form1::Button1_Click);

                     //

                     // groupBox2

                     //

                     this->groupBox2->Controls->Add(this->Button10);

                     this->groupBox2->Controls->Add(this->label9);

                     this->groupBox2->Controls->Add(this->Label6);

                     this->groupBox2->Controls->Add(this->Label5);

                     this->groupBox2->Controls->Add(this->TextBox8);

                     this->groupBox2->Controls->Add(this->TextBox7);

                     this->groupBox2->Controls->Add(this->TextBox6);

                     this->groupBox2->Controls->Add(this->Label4);

                     this->groupBox2->Controls->Add(this->Label3);

                     this->groupBox2->Controls->Add(this->TextBox5);

                     this->groupBox2->Controls->Add(this->TextBox4);

                     this->groupBox2->Location = System::Drawing::Point(159, 12);

                     this->groupBox2->Name = L"groupBox2";

                     this->groupBox2->Size = System::Drawing::Size(273, 148);

                     this->groupBox2->TabIndex = 46;

                     this->groupBox2->TabStop = false;

                     this->groupBox2->Text = L"Modify";

                     //

                     // Button10

                     //

                     this->Button10->Location = System::Drawing::Point(187, 52);

                     this->Button10->Name = L"Button10";

                     this->Button10->Size = System::Drawing::Size(77, 56);

                     this->Button10->TabIndex = 25;

                     this->Button10->Text = L"Modify";

                     this->Button10->UseVisualStyleBackColor = true;

                     this->Button10->Click += gcnew System::EventHandler(this, &Form1::Button10_Click);

                     //

                     // label9

                     //

                     this->label9->AutoSize = true;

                     this->label9->Location = System::Drawing::Point(3, 120);

                     this->label9->Name = L"label9";

                     this->label9->Size = System::Drawing::Size(81, 13);

                     this->label9->TabIndex = 24;

                     this->label9->Text = L"Modified Phone";

                     //

                     // Label6

                     //

                     this->Label6->AutoSize = true;

                     this->Label6->Location = System::Drawing::Point(4, 95);

                     this->Label6->Name = L"Label6";

                     this->Label6->Size = System::Drawing::Size(70, 13);

                     this->Label6->TabIndex = 23;

                     this->Label6->Text = L"Modified Last";

                     //

                     // Label5

                     //

                     this->Label5->AutoSize = true;

                     this->Label5->Location = System::Drawing::Point(6, 72);

                     this->Label5->Name = L"Label5";

                     this->Label5->Size = System::Drawing::Size(69, 13);

                     this->Label5->TabIndex = 22;

                     this->Label5->Text = L"Modified First";

                     //

                     // TextBox8

                     //

                     this->TextBox8->Location = System::Drawing::Point(85, 118);

                     this->TextBox8->Name = L"TextBox8";

                     this->TextBox8->Size = System::Drawing::Size(95, 20);

                     this->TextBox8->TabIndex = 21;

                     //

                     // TextBox7

                     //

                     this->TextBox7->Location = System::Drawing::Point(85, 94);

                     this->TextBox7->Name = L"TextBox7";

                     this->TextBox7->Size = System::Drawing::Size(95, 20);

                     this->TextBox7->TabIndex = 20;

                     //

                     // TextBox6

                     //

                     this->TextBox6->Location = System::Drawing::Point(86, 69);

                     this->TextBox6->Name = L"TextBox6";

                     this->TextBox6->Size = System::Drawing::Size(95, 20);

                     this->TextBox6->TabIndex = 19;

                     //

                     // Label4

                     //

                     this->Label4->AutoSize = true;

                     this->Label4->Location = System::Drawing::Point(2, 47);

                     this->Label4->Name = L"Label4";

                     this->Label4->Size = System::Drawing::Size(27, 13);

                     this->Label4->TabIndex = 18;

                     this->Label4->Text = L"Last";

                     //

                     // Label3

                     //

                     this->Label3->AutoSize = true;

                     this->Label3->Location = System::Drawing::Point(4, 25);

                     this->Label3->Name = L"Label3";

                     this->Label3->Size = System::Drawing::Size(26, 13);

                     this->Label3->TabIndex = 17;

                     this->Label3->Text = L"First";

                     //

                     // TextBox5

                     //

                     this->TextBox5->Location = System::Drawing::Point(86, 44);

                     this->TextBox5->Name = L"TextBox5";

                     this->TextBox5->Size = System::Drawing::Size(95, 20);

                     this->TextBox5->TabIndex = 16;

                     //

                     // TextBox4

                     //

                     this->TextBox4->Location = System::Drawing::Point(86, 20);

                     this->TextBox4->Name = L"TextBox4";

                     this->TextBox4->Size = System::Drawing::Size(95, 20);

                     this->TextBox4->TabIndex = 15;

                     //

                     // ListBox1

                     //

                     this->ListBox1->FormattingEnabled = true;

                     this->ListBox1->Location = System::Drawing::Point(259, 174);

                     this->ListBox1->Name = L"ListBox1";

                     this->ListBox1->Size = System::Drawing::Size(328, 173);

                     this->ListBox1->TabIndex = 47;

                     //

                     // pictureBox1

                     //

                     this->pictureBox1->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;

                     this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"pictureBox1.Image")));

                     this->pictureBox1->Location = System::Drawing::Point(448, 16);

                     this->pictureBox1->Name = L"pictureBox1";

                     this->pictureBox1->Size = System::Drawing::Size(139, 144);

                     this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;

                     this->pictureBox1->TabIndex = 48;

                     this->pictureBox1->TabStop = false;

                     //

                     // Form1

                     //

                     this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);

                     this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

                     this->ClientSize = System::Drawing::Size(599, 357);

                     this->Controls->Add(this->pictureBox1);

                     this->Controls->Add(this->ListBox1);

                     this->Controls->Add(this->groupBox2);

                     this->Controls->Add(this->Button8);

                     this->Controls->Add(this->GroupBox1);

                     this->Controls->Add(this->Button9);

                     this->Controls->Add(this->Button4);

                     this->Controls->Add(this->Button7);

                     this->Controls->Add(this->Button1);

                     this->Controls->Add(this->Button6);

                     this->Controls->Add(this->Button2);

                     this->Controls->Add(this->Button5);

                     this->Controls->Add(this->Button3);

                     this->Icon = (cli::safe_cast<System::Drawing::Icon^  >(resources->GetObject(L"$this.Icon")));

                     this->Name = L"Form1";

                     this->Text = L"PhoneBook Program";

                     this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

                     this->GroupBox1->ResumeLayout(false);

                     this->GroupBox1->PerformLayout();

                     this->groupBox2->ResumeLayout(false);

                     this->groupBox2->PerformLayout();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->EndInit();

                     this->ResumeLayout(false);

 

              }

#pragma endregion

       private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

                      }

private: System::Void Button1_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

// try this for Windows 7 if the first connection string doesn't work

//myConnection->ConnectionString = "Provider =Microsoft.Jet.OLEDB.4.0; Data Source =c:\\PhoneBook.mdb; Persist Security Info =False;";

 

                     

                      try

                      {

                  myConnection->Open();

                  ListBox1->Items->Clear();

                  ListBox1->Items->Add("Connection made");

                             myConnection->Close();

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");

                      }

               }

private: System::Void Button2_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      try

                      {

                 String ^queryString = "select count(*) as RecordCount from Table1";

                            String ^result="";

                            //OleDbDataReader ^reader;// =gcnew OleDbDataReader ;//command.ExecuteReader();

               

                            myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

                 OleDbCommand ^SqlCommand=gcnew OleDbCommand(queryString, myConnection); 

                            myConnection->Open();

                             if(myConnection->State !=ConnectionState::Open)

                             {

                                    ListBox1->Items->Clear();

                                    ListBox1->Items->Add("Error");

                                    myConnection->Close();

                             }

                             else

                             {

                                    ListBox1->Items->Clear();

                                    result = SqlCommand->ExecuteScalar()->ToString();

                                    ListBox1->Items->Add(result);

                                    myConnection->Close();

                             }

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");

                      }

               }

private: System::Void Button3_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      try

                      {

                 String ^queryString = "select * from Table1";

                            OleDbDataReader ^result;//

                

                            myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

                 OleDbCommand ^SqlCommand=gcnew OleDbCommand(queryString, myConnection); 

                            myConnection->Open();

                             if(myConnection->State !=ConnectionState::Open)

                             {

                                    ListBox1->Items->Clear();

                                    ListBox1->Items->Add("Error");

                                    myConnection->Close();

                             }

                             else

                             {

                                    ListBox1->Items->Clear();

                                    result = SqlCommand->ExecuteReader();

                                    while( result->Read())

                                    {

                          ListBox1->Items->Add(result->GetValue(1)->ToString() + " " + result->GetValue(2)->ToString()+ " " + result->GetValue(3)->ToString());

                                    }

                                    result->Close();

                                    myConnection->Close();

                             }

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");

                      }

               }

private: System::Void Button4_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      try

                      {

                 String ^queryString = "select * from Table1 order by firstName";

                            OleDbDataReader ^result;// =gcnew OleDbDataReader ;//command.ExecuteReader();    

                            myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

                 OleDbCommand ^SqlCommand=gcnew OleDbCommand(queryString, myConnection); 

                            myConnection->Open();

                             if(myConnection->State !=ConnectionState::Open)

                             {

                                    ListBox1->Items->Clear();

                                    ListBox1->Items->Add("Error");

                                    myConnection->Close();

                             }

                             else

                             {

                                    ListBox1->Items->Clear();

                                    result = SqlCommand->ExecuteReader();

                                    while( result->Read())

                                    {

                           ListBox1->Items->Add( result->GetValue(2)->ToString()+" " + result->GetValue(1)->ToString() + " " + result->GetValue(3)->ToString());

                                    }

                      result->Close();

                                 myConnection->Close();

                       }

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");;

                      }

               }

private: System::Void Button5_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      try

                      {

                 String ^queryString = "select * from Table1 order by lastName";

                            OleDbDataReader ^result;// =gcnew OleDbDataReader ;//command.ExecuteReader();               

                            myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

                 OleDbCommand ^SqlCommand=gcnew OleDbCommand(queryString, myConnection); 

                            myConnection->Open();

                             if(myConnection->State !=ConnectionState::Open)

                             {

 

                                    ListBox1->Items->Clear();

                                    ListBox1->Items->Add("Error");

                                    myConnection->Close();

                             }

                             else

                             {

                                    ListBox1->Items->Clear();

                                    result = SqlCommand->ExecuteReader();

                                    while( result->Read())

                                    {

                           ListBox1->Items->Add(result->GetValue(1)->ToString() + " " + result->GetValue(2)->ToString()+ " " + result->GetValue(3)->ToString());

                                    }

                                    result->Close();

                                    myConnection->Close();

                             }

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");;

                      }

               }

 

private: System::Void Button6_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      ListBox1->Items->Clear();

 

                            //if( myConnection->Equals(NULL) )

                         //if( myConnection->Equals(nullptr) )

                      if( myConnection->Equals(nullptr ))

                            {

                                   ListBox1->Items->Add("No Connection to close");

                                   return;

                            }

                      else

                      {

                            ListBox1->Items->Add("Connection closed");

                            myConnection->Close();

                      }

               }

private: System::Void Button7_Click(System::Object^  sender, System::EventArgs^  e)

               {

                        int found = -1;

               String ^firstName="";

                        String ^lastName="";

                        String ^sqlFind="";

                        firstName=TextBox1->Text->Trim();

                        lastName=TextBox2->Text->Trim();

                        String ^FLname="";

                        if (TextBox1->Text->Trim()== "" && TextBox2->Text->Trim() == "")

                           {

                        MessageBox::Show("Enter First Name or last name or first Name and last Name");

                        return;

                           }

                         try

                         {

                 String ^queryString = "select * from Table1 Where firstName like '%" + firstName + "%' and lastName like '%" + lastName + "%'";

                            OleDbDataReader ^result;// =gcnew OleDbDataReader ;//command.ExecuteReader();               

                            myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

                 OleDbCommand ^SqlCommand=gcnew OleDbCommand(queryString, myConnection); 

                            myConnection->Open();

                             if(myConnection->State !=ConnectionState::Open)

                             {

 

                                    ListBox1->Items->Clear();

                                    ListBox1->Items->Add("Error");

                                    myConnection->Close();

                             }

                             else

                             {

                                    ListBox1->Items->Clear();

                                    result = SqlCommand->ExecuteReader();

                                    while( result->Read())

                                    {

                           ListBox1->Items->Add(result->GetValue(1)->ToString() + " " + result->GetValue(2)->ToString()+ " " + result->GetValue(3)->ToString());

                                            TextBox3->Text=result->GetValue(3)->ToString();

                                            FLname=result->GetValue(2)->ToString()+result->GetValue(1)->ToString()+".jpg";

                                            found = found + 1;

                                    }

                                    result->Close();

                                    myConnection->Close();

                                    if (found == -1)

                                    {

                                           ListBox1->Items->Add("No records found");

                                    }

                                    else

                                    if(IO::File::Exists(FLname))

                                    {    //checks if jpg (picture) file present in directory                            

                                           pictureBox1->Image=Image::FromFile(FLname);

                                    }

                                    else

                                    {

                                           pictureBox1->Image=Image::FromFile("Default.jpg");

                                    }

                             }

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");;

                      }

               }

private: System::Void Button8_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      ListBox1->Items->Clear();

               String ^sqlDelete="";

               String ^firstName="";

               String ^lastName="";

                        int result=-1;

                        firstName=TextBox1->Text->Trim();

                        lastName=TextBox2->Text->Trim();

                        if (TextBox1->Text->Trim()== "" && TextBox2->Text->Trim() == "")

                           {

                        MessageBox::Show("Enter First Name and Last name ");

                        return;

                           }

                         try

                         {

                 String ^queryString = "delete from Table1 Where lastName = '" + lastName + "' and firstName = '" + firstName + "'";

                            //OleDbDataReader ^result;// =gcnew OleDbDataReader ;//command.ExecuteReader();               

                            myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

                 OleDbCommand ^SqlCommand=gcnew OleDbCommand(queryString, myConnection); 

                            myConnection->Open();

                             if(myConnection->State !=ConnectionState::Open)

                             {

 

                                    ListBox1->Items->Clear();

                                    ListBox1->Items->Add("Error");

                                    myConnection->Close();

                             }

                             else

                             {

                                    ListBox1->Items->Clear();

                                    result = SqlCommand->ExecuteNonQuery();

                                    myConnection->Close();

                                    if( result== 0)

                                    {

                         ListBox1->Items->Add("No records deleted!");

                                    }

                                    else

                                    {

                          ListBox1->Items->Add(result.ToString() + " record(s) deleted!");

                                    }

                             }

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");;

                      }

               }

private: System::Void Button9_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      ListBox1->Items->Clear();

               String ^sqlDelete="";

               String ^firstName="";

               String ^lastName="";

                        String ^phone="";

                        int result=-1;

                        firstName=TextBox1->Text->Trim();

                        lastName=TextBox2->Text->Trim();

                        phone=TextBox3->Text->Trim();

                        if (TextBox1->Text->Trim()== "" && TextBox2->Text->Trim() == "" && TextBox3->Text->Trim() == "")

                           {

                        MessageBox::Show("Enter First Name, Last name, and Phone ");

                        return;

                           }

                         try

                         {

                 String ^queryString = "INSERT INTO Table1(firstName, lastName, phone) VALUES('" + firstName + "', '" + lastName + "', '" + phone+ "')";

                            //OleDbDataReader ^result;// =gcnew OleDbDataReader ;//command.ExecuteReader();               

                            myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

                 OleDbCommand ^SqlCommand=gcnew OleDbCommand(queryString, myConnection); 

                            myConnection->Open();

                             if(myConnection->State !=ConnectionState::Open)

                             {

 

                                    ListBox1->Items->Clear();

                                    ListBox1->Items->Add("Error");

                                    myConnection->Close();

                             }

                              else

                             {

                                    ListBox1->Items->Clear();

                                    result = SqlCommand->ExecuteNonQuery();

                                    myConnection->Close();

                                    if( result== 0)

                                    {

                         ListBox1->Items->Add("No records inserted!");

                                    }

                                    else

                                    {

                          ListBox1->Items->Add( "Record inserted!");

                                    }

                             }

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");

                      }

               }

private: System::Void Button10_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      OleDbDataReader ^result;

               String ^sqlDelete="";

               String ^firstName="";

                        String ^newFirst="";

               String ^lastName="";

                        String ^newLast="";

                        String ^phone="";

                        String ^newPhone="";

                        String ^sqlFind;                  

                        String  ^sqlUpdate="";

                        int upDateCount=-1;

                        //int result=-1;

                     ListBox1->Items->Clear();

                        firstName=TextBox4->Text->Trim();

                        lastName=TextBox5->Text->Trim();

 

                        newFirst=TextBox6->Text->Trim();

                        newLast=TextBox7->Text->Trim();

                        newPhone=TextBox8->Text->Trim();

 

                        sqlFind= "select * from Table1 Where lastName = '" + lastName + "' and firstName = '" + firstName + "'";

                        if (TextBox4->Text->Trim()== "" && TextBox5->Text->Trim() == ""

                              && TextBox6->Text->Trim() == ""&& TextBox7->Text->Trim() == ""

                              && TextBox8->Text->Trim() == "")

                           {

                        MessageBox::Show("Fill in Modification Fields");

                        return;

                           }

                         try

                         {

                                  //sqlFind

                 //String ^queryString = "INSERT INTO Table1(firstName, lastName, phone) VALUES('" + firstName + "', '" + lastName + "', '" + phone+ "')";

                            //OleDbDataReader ^result;// =gcnew OleDbDataReader ;//command.ExecuteReader();               

                            myConnection->ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =c:\\PhoneBook.accdb; Persist Security Info =False;";

                 OleDbCommand ^SqlCommand=gcnew OleDbCommand(sqlFind, myConnection); 

                            myConnection->Open();

                             //MessageBox::Show(sqlFind);

                             if(myConnection->State !=ConnectionState::Open)

                             {

 

                                    ListBox1->Items->Clear();

                                    ListBox1->Items->Add("Error");

                                    myConnection->Close();

                             }

                             else

                             {

                                    ListBox1->Items->Clear();

                                    result = SqlCommand->ExecuteReader();

                                    if ( !result->HasRows)

                                     {

                                            //MessageBox::Show(sqlFind);

                                            ListBox1->Items->Add("No records found to modify");

                                            //myConnection->Close();

                                     }

                                    else

                                    {

                                           result->Close();

                                           sqlUpdate = "update Table1 set firstName = '" + newFirst + "', lastName = '" + newLast +  "', phone = '" + newPhone + "' where firstName = '" + firstName + "' and lastName = '" + lastName + "'";

                                           MessageBox::Show(sqlUpdate);

                                           OleDbCommand ^sqlUpdateCommand=gcnew OleDbCommand(sqlUpdate, myConnection);

                                           upDateCount=sqlUpdateCommand->ExecuteNonQuery();

                                           if(upDateCount == 0)

                                           {

                                ListBox1->Items->Add("No records updated!");

                                           }

                                           else

                                           {

                                ListBox1->Items->Add("Record updated!");           

                                        }                                          

                                    }

                                     myConnection->Close();

                                    }

                      }

                      catch (Exception ^e)

                      {

                MessageBox::Show(e->Message, "Error");;

                      }

               }

};

}

 

 

 

 

 (Back) 


Tutorial 14: Making A Setup or Deployment Package of a Microsoft Windows  Program in C++ By Russell Pitts  

        Bring up the project you are working on as a Microsoft Windows Form Application which you wish to distribute.   Here for the sake of simplicity I will use a simple project that has a button on it and a label called “HelloWorld”.  If the button is clicked a message appears in the label that says hello.  It looks as follows: 

Sample Program for Deployment

        On the button is the simple code:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)                    {

                         label1->Text="Hello!";

                   }

        Rebuild the Project so the project and its files are saved.  Now go to File>New Project>Other Project types>Setup and Deployment>Setup Wizard  as shown in the following figure:

Setting up the project

        Under Solution, select “Add to Solution” and then enter OK.    In the setup Wizard, 1 of 5, that follows enter Next...

Welcome to the Setup Project Wizard

        In the next window, 2 of 5, go with the default and select Next:

Choose a Project type

        In the next window, 3 of 5, select Primary output from HelloWorld and Resource Satellite DLL's from HelloWorld and select Finish.

Choose project ouputs to include

        Open the Solution explorer for the project and right click on Setup1 and select build as is shown in the following figure:

Build Menu

        Navigate in Windows Explorer to the debug folder of Setup1 of your  HelloWorld Project as illustrated in the following figure and copy the entire debug folder

Explorer Window of Project

         Then paste the debug folder someplace else and change the name of the debug folder to Setup.  These two files Setup1.msi and setup.exe in this folder are all you need to install the package.

Explorer Window

 (Back) 

 


©All rights reserved by James Krumm. Originally made available at www.caspercomsci.com. Materials here can be used, and redistributed, provided proper reference is made to the origin and author(s) of these materials. Please send any corrections or suggestions to jkrumm@caspercollege.edu. Last modified May 15, 2012.


To find out more about the Casper College Computer Science Program contact us at:

James Krumm
Department Head
Computer Science,
Wold Physical Sciences Building,
Casper College,
125 College Drive,
Casper, Wyoming 82601
(307) 268-2519 jkrumm@caspercollege.edu

[Return to Home Page]

|Home| |Computer Science| |Casper College| |Java Source Code| |C++ Source Code| |Visual C++.NET| |Visual Basic| |Assembly Source Code| |Linux| |Dice Program|

|Wyoming| |Casper Area| |American Album| |Personal Album| |Hawaii| |Florida| |Denmark| |Greece| |Paris| |London| |Amsterdam| |Cozumel| |Links| |Sitemap|