A simple 2D Color Slot Machine in Dark GDK

I’m sure every one of us is familiar with slot machine or fruit machine game. Today we will be making a slight version of that game, and we are going to name it as “Color Slot Machine”. There are several elements missing in this game such as the game title screen and the game overview screen so I’ll just explain to you the mechanics of the game. Before the game starts you have an initial account of 100000. To play the game, click on the Spin button. After clicking on the Spin button the computer will generate random colors and your score depends upon the generated color. The scoring system is presented below:

ColorWin
Red-Green-Blue+2000
Red-Red-Red+1000
Green-Green-Green+1000
Blue-Blue-Blue+1000
Others-1000
The following steps demonstrate how to create this game:

1.Prepare the images that will be needed in your game. You can use Ms-Paint, Photoshop or GIMP. The following images are required for this game:



2. After preparing the images, Start Visual C++>File>New>Projects>Wizards>Select Dark GDK-Game>Type “Color Machine” in the name textbox (no quotes).

3. Assuming that you have saved the project in the default directory, minimize Microsoft Visual C++ then go to My Documents>Visual Studio 2008>Projects>Color Machine>Color Machine>Then paste the images that you have made in Step 1.



4. Maximize Visual C++>View>Solution Explorer>Double-click Main.cpp. The following should then come into view:

// Dark GDK - The Game Creators - www.thegamecreators.com

// the wizard has created a very simple project that uses Dark GDK
// it contains the basic code for a GDK application

// whenever using Dark GDK you must ensure you include the header file
#include "DarkGDK.h"

// the main entry point for the application is this function
void DarkGDK ( void )
{
 // turn on sync rate and set maximum rate to 60 fps
 dbSyncOn   ( );
 dbSyncRate ( 60 );

 // our main loop
 while ( LoopGDK ( ) )
 {
  // update the screen
  dbSync ( );
 }

 // return back to windows
 return;
}

5. Locate the line #include "DarkGDK.h" then declare the following variables below it:
//handles the spriteid of the left box
int intred;
//handles the spriteid of the middle box
int intgreen;
//handles the spriteid of the right box
int intblue;
//handles our loop
int intcounter;
//determines if the spin button has been clicked
int intclicked;
//displays our status text
char* chrmessage;
//handles the balance
int intbalance=100000;

6. Locate the line dbSynRate(60); then replace the 60 with 10 so that dark GDK will try to play 10 frames per second and our loop will not play funny , then type the following after it:
//sets the window title
dbSetWindowTitle("Color Slot Machine");
//sets the window size
dbSetWindowSize(400,400);
//loads our images
dbLoadImage("red.png",1);
dbLoadImage("green.png",2);
dbLoadImage("blue.png",3);
dbLoadImage("backdrop.png",4);
dbLoadImage("Spin.png",5);
dbLoadImage("pointer.png",6);
//displays our images
dbSprite(4,0,0,4);
//sets our backdrop alpha transparency
//so that our text will be visible
dbSetSpriteAlpha(4,150);
dbSprite(5,240,380,5);
dbSprite(1,130,100,1);
dbSprite(2,260,100,2);
dbSprite(3,390,100,3);

7. Locate the Line while ( LoopGDK ( ) ) then type the following after the open curly brace:
//sets text size to 30 points
dbSetTextSize(30);
//displays the balance
//I still don’t know how to concanate text
dbText(0,0,"Balance:");
dbText(150,0,dbStr(intbalance));
  //displays our status text
  dbText(250,250,chrmessage);
  //pessimistic programming
  //assume that the button has not yet been clicked
  intclicked=0;
  //hides our customized mouse pointer
  //so that only the mouse pointer is visible
  dbHideSprite(6);
  //Enables dbRnd to generate an unpredictable
  //random number generation
  dbRandomize(dbTimer());
  dbSetSprite(6,1,100);
  //enables our sprite to follow the mouse
  dbSprite(6,dbMouseX(),dbMouseY(),6);
  //if our hidden sprite collided with the mouse
  //and the button has been clicked
  if(dbSpriteHit(6,5)==1 && dbMouseClick()==1)
  {
  //assigns 1 to inclicked variable
  //resets the value of chrmessage
  intclicked=1;
  chrmessage="";
  //generate a random color 10 times
  for(intcounter=1;intcounter<=10;intcounter++)
  {
   intred=1 + dbRnd(2);
   intblue=1 + dbRnd(2);
   intgreen=dbRnd(2)+1;
   dbSprite(1,130,100,intred);
   dbSprite(2,260,100,intgreen);
   dbSprite(3,390,100,intblue);
   dbSync();
  }
  }
  
  //check if the button has been clicked
  //if it was clicked then

  if (intclicked==1)
  {
   //check for color matches
   if (intred==1 && intblue==1 && intgreen==1)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
  
   }
   else if (intred==2 && intblue==2 && intgreen==2)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
   }
   else if (intred==3 && intblue==3 && intgreen==3)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
   }
   else if (intred==1 && intblue==2 && intgreen==3)
   {
   chrmessage="You win 2000!";
   intbalance=intbalance+1000;
   }
   //if no color matches then
   else
   {
   chrmessage="You Lose!";
   intbalance=intbalance-1000;
   }
  }
  //if the balance is less than or equal to zero
  if (intbalance<=0)
  {
  dbCLS();
  dbSetTextSize(32);
  dbText(180,250,"Insufficient balance");
  dbText(250,300,"GAME OVER");
  dbSync();
  dbWait(4000);
  return;
 }
8. Let’s have a look of our code once again and this time, crappy comments ommitted.
// Dark GDK - The Game Creators - www.thegamecreators.com

// the wizard has created a very simple project that uses Dark GDK
// it contains the basic code for a GDK application

// whenever using Dark GDK you must ensure you include the header file
#include "DarkGDK.h"
int intred;
int intblue;
int intgreen;
int intcounter;
int intclicked;
char* chrmessage;
int intbalance=100000;
// the main entry point for the application is this function
void DarkGDK ( void )
{

 // turn on sync rate and set maximum rate to 60 fps
 dbSyncOn   ( );
 dbSyncRate ( 20 );
 dbSetWindowTitle("Color Slot Machine");
 dbSetWindowSize(400,400);
 dbSetGamma(500,255,500);
 dbLoadImage("red.png",1);
 dbLoadImage("green.png",2);
 dbLoadImage("blue.png",3);
 dbLoadImage("backdrop.png",4);
 dbLoadImage("Spin.png",5);
 dbLoadImage("pointer.png",6);
 dbSprite(4,0,0,4);
 dbSetSpriteAlpha(4,150);
 dbSprite(5,240,380,5);
 dbSprite(1,130,100,1);
 dbSprite(2,260,100,2);
 dbSprite(3,390,100,3);

 // our main loop
 while ( LoopGDK ( ) )
 {

  dbSetTextSize(30);
  dbText(0,0,"Balance:");
  dbText(150,0,dbStr(intbalance));
  dbText(250,250,chrmessage);
  intclicked=0;
  dbHideSprite(6);
  dbRandomize(dbTimer());
  dbSetSprite(6,1,100);
  dbSprite(6,dbMouseX(),dbMouseY(),6);
  if(dbSpriteHit(6,5)==1 && dbMouseClick()==1)
  {
  intclicked=1;
  chrmessage="";
   for(intcounter=1;intcounter<=10;intcounter++)
   {
   intred=1 + dbRnd(2);
   intblue=1 + dbRnd(2);
   intgreen=dbRnd(2)+1;
   dbSprite(1,130,100,intred);
   dbSprite(2,260,100,intgreen);
   dbSprite(3,390,100,intblue);
   dbSync();
   }
  }

  if (intclicked==1)
  {
   if (intred==1 && intblue==1 && intgreen==1)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
  
   }
   else if (intred==2 && intblue==2 && intgreen==2)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
   }
   else if (intred==3 && intblue==3 && intgreen==3)
   {
   chrmessage="You win 1000!";
   intbalance=intbalance+1000;
   }
   else if (intred==1 && intblue==2 && intgreen==3)
   {
   chrmessage="You win 2000!";
   intbalance=intbalance+1000;
   }
   else
   {
   chrmessage="You Lose!";
   intbalance=intbalance-1000;
   }
  }
  
  if (intbalance<=0)
  {
  dbCLS();
  dbSetTextSize(32);
  dbText(180,250,"Insufficient balance");
  dbText(250,300,"GAME OVER");
  dbSync();
  dbWait(4000);
  return;
  }

  // update the screen
  
  dbSync ( );
 }

 // return back to windows
 return;
}
9. Press F5 to test our game. Click the Spin button and see what happens.

Binding a fieldname to a control programmatically in Visual J#

Before the Database Connection and Binding process I want you to make an Ms-Access database file named “dbEmployee” containing a table named “tblEmployee”. Use the following specifications:
Field Name Data Type Description
chrempno text Handles employee id
chrfname text Handles employee’s name
chrlname text Holds employee’s last name

After designing the structure of your table, you can enter appropriate values for each field. For instance:
chrempno chrfname Chrlname
2010A John Doe

Now that we are done creating a table and adding appropriate values to it, we can now link to that table and bind the fields to our windows application control by following these steps:

1. Start>All programs>Visual J# 2005 Express Edition.

2. Click File>New>Project>Select Windows Application from the windows studio installed templates then click Ok.

3. A new form will appear. Before adding appropriate controls to our form let us first establish a connection to our dbEmployee database file. To do this we will use a database access tool called OleDbDataAdapter. OleDbDataAdapter will enable us to set the filename of a database file and the name of the table that we wanted to be made available in our project. It also permits us to set-up how the record values will be displayed on our form by using an appropriate SQL statement.

4. By default, OleDbDataAdapter is not shown on the Visual J# 2005 Express control toolbox, to add it, click Tools>Choose control toolbox>Type “ole” (no quotes ) on the filter textbox then check all the items that starts with “ole” and finally click the Ok button. OleDbDataAdapter should now appear on your toolbox.

5. Expand the All Windows Forms toolbox category then double-click OleDbDataAdapter.

6. A Data Adapter configuration wizard will then appear. Click the new connection button>Select Microsoft Access Database File from the data source list.

7. Click the browse button then locate your dbEmployee.mdb file then click the Ok button.

8. Click Next>A message box containing the following prompt will appear:
“The connection you selected uses a local data file that is not in the current project would you like to your project for the connection? If you copy the data file to your project, it will be copied to the project’s output directory”> just click the Ok button then click next.

9. A Generate SQL statement, type “SELECT * FROM tblEmployee” (no quotes) this will export all the record value of our table to our project then. Click Next after typing the SQL statement and finally click the Finish Button.

10. After specifying the table name, right-click OleDbDataAdapter1 from the bottom portion of Visual J# IDE then click Generate Data Set then click the Ok button. If you are wondering what a dataset is, a Dataset is an imaginary box the holds the field names of your table. It is use a temporary storage box for table data.

11. At this point, you will need to design the interface of your application. Double-click the label tool. In the properties window, change its text to “Employee number:” (no quotes).

12. Double-click the label tool and put it in the right-side of your Employee number label. Change its name to Empnumberlabel.

13. Add another label below the Employee number label and change its text to “Firstname:” (no quotes). Put a label on its right side and name it Fnamelabel.

14. Add another label below the Firstname label and change its text to “Lastname:” (no quotes). Put another label on its right side and name it Lnamelabel.

15. Double-click your form, type the following code:
//fills our dataset with record values
this.oleDbDataAdapter1.Fill(this.dataSet11);
//Use the dataset methods collection to retrieve the record values
//The get_Item() method after the get_Rows() method retrieves the table row value
//while the last get_Item retrieves the table column value
Empnumberlabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(0)));
//The index number of the first table row is 0, the second row is 1 and so on.
//Column index number starts from 0, the second table column is 1 and so on.
Fnamelabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(1)));
//Dataset collection methods returns an object data that is why we use the 
//String.valueOf data conversion function to convert it to string.
Lnamelabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(2)));
16. Your code should now look like this:
private void Form1_Load(Object sender, System.EventArgs e)
{
this.oleDbDataAdapter1.Fill(this.dataSet11);
Empnumberlabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(0)));
Fnamelabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(1)));
Lnamelabel.set_Text(String.valueOf(dataSet11.get_Tables().get_Item("tblEmployee").get_Rows().get_Item(0).get_Item(2)));
}
17. Press F5 to test your application.You should now see the following output:


Search a Record Value in Microsoft Visual Basic 2008 Express Edition

As you may probably know, standard navigational buttons are only effective if you are managing few record values but when it comes to billions of records a search module is considerably significant. Search module allows you to quickly test whether a specific record value exists in a multi-records database.
I’d been using Visual Basic 2008 Express Edition for a while now but I can hardly find a method appropriate in searching record. No wonder why most questions that relate to searching a record values in nearly all web forums are unanswered. Perhaps there are other methods that I may not know but here’s an approach that I discovered through inquiries and experimentation.

To give you an idea of how to do it, let us first examine the common algorithm shared by most search modules.

1. First, a search text is entered in a text box as an input.

2. That text is then compared to the first record or beginning of file(BOF). If the first record is equal to the search text, a corresponding record is then displayed.

3. If the search text is not equal to the first record, the record pointer is moved to the next record and a search text is then compared to that record.

4. The record pointer is continuously incremented until a match is found and the end of file(EOF) has not yet been reached.


At this point we will now apply these pseudo codes into our search module. Though that may seem simple, it is more complicated to use BOF and EOF functions in Visual Basic 2008 than in lower versions of Visual Basic. I barely know how to use them on text files, which leave us no choice but to do everything the lengthy yet easiest way. The following steps demonstrate how:


1. Design an Ms-Access 2003 database file named “dbnames” using the following field structure:

Field nameData TypeDescription
chrfname text Handles the firstname of whoever
chrlname Text Handles the lastname


2. Add the following values.

chrfname chrlname
John Doe
Jean Doe
Jane Doe

3. Save your table as “tblNames”.

4. After designing your table, close Ms-Access then click Start>Select All Programs then Click Visual Basic 2008 Express Edition. The Visual Basic 2008 Express Edition IDE should then appear.

5. Click the File menu then Select New Project.

6. The New Project dialog box should then come into view >Double-click Windows Forms Application from the available templates.

7. A new form will appear. Before adding appropriate controls to our form let us first establish a connection to our dbnames database file. To do this we will use a database access tool called OleDbDataAdapter. OleDbDataAdapter will enable us to set the filename of a database file and the name of the table that we wanted to be made available in our project. It also permits us to set-up how the record values will be displayed on our form by using an appropriate SQL statement.

8. By default, OleDbDataAdapter is not shown on the VB 2008 control toolbox, to add it, click Tools>Choose control toolbox>Type “ole” (no quotes ) on the filter textbox then check all the items that starts with “ole” and finally click the Ok button. OleDbDataAdapter should now appear on your toolbox.

9. Expand the All Windows Forms toolbox category then double-click OleDbDataAdapter.

10. A Data Adapter configuration wizard will then appear. Click the new connection button>Select Microsoft Access Database File from the data source list.

11. Click the browse button then locate your dbicons.mdb file then click the Ok button.

12. Click Next>A message box containing the following prompt will appear:
“The connection you selected uses a local data file that is not in the current project would you like to your project for the connection? If you copy the data file to your project, it will be copied to the project’s output directory”> just click the Ok button then click next.

13. A Generate SQL statement, type “SELECT * FROM tblNames” (no quotes) this will export all the record value of our table to our project then. Click Next after typing the SQL statement and finally click the Finish Button.

14. After specifying the table name, right-click OleDbDataAdapter1 from the bottom portion of VB 2008 IDE then click Generate Data Set then click the Ok button. If you are wondering what a dataset is, a Dataset is an imaginary box the holds the field names of your table. It is use a temporary storage box for table data.

15. At this point we will now design the interface of our application. Arrange your controls as follows:



Note: Those texts that appear beside each control are the suggested names for our form controls in this module. To change the value of the name property of each control, just click each individual control then locate the name property in the properties window then assign those descriptive names in our illustration correspondingly.

16. Click the label named Namelabel. In the properties window, locate data bindings>text>form1 instance>Dataset11>tblnames>chrfname. This will bind your field value to your Namelabel control.

17. Click the label named Lnamelabel. In the properties window, locate data bindings>text>form1 instance>Dataset11>tblnames>chrlname. This will bind your field value to your Lnamelabel control.

18. Double-click your form, type the following code:
'Populates your dataset with record values
OleDbDataAdapter1.Fill(DataSet11)

19. Double-click your control named SearchButton then type the following:

'handles the row index number of our table
Dim introws as integer
'determines whether the record is found or not
Dim blnfound as Boolean
'at the start let us assume that a match has no yet been found
'this is called pessimistic programming or something
blnfound=false
'Holds the search text from the textbox 
Dim strtext as String
'Holds the record value from the chrfname field 
Dim strname as String
'Holds the total number of records
Dim inttotrec as Integer
'this is our EOF
inttotrec=Dataset11.Tables("tblNames").Rows.Count
'Moves the record pointer to the first record
'which has a row index number of zero
introws = 0
'Converts the value of the first record of our chrfname field to capital
'letter and assign it to a variable named strname
strname = UCase(DataSet11.Tables("tblNames").Rows(introws).Item("chrfname"))
'Converts the text entered in our search textbox to Uppercase
'The purpose of converting both record values and search text to upper case
'is to compare both values in uppercase form regardless of whatever
'case they were typed initially
strtext = UCase(SearchTextBox.Text)
'If the searchtext is equal to our record then
If (strtext = strname) Then
'assign true to our blnfound variable
'will be used later whether to display or not
'to display our message box
blnfound = True
'display the record values on their corresponding controls
'to understand how to view records on your form
'visit www.homeandlearn.com
'this site helped me a lot when I was just starting .Net programming
'thanks www.homeandlearn.com
NameLabel.Text=DataSet11.Tables("tblNames").Rows(introws).Item("chrfname")
LnameLabel.Text = DataSet11.Tables("tblEmployee").Rows(introws).Item("chrlname")
End If
'if not equal to the first record then
While (strtext <> strname) And (introws < inttotrec - 1)
'increment the record pointer 
introws = introws + 1
'assign the value of the next record pointer to strname
strname = UCase(DataSet11.Tables("tblNames").Rows(introws).Item("chrfname"))
'tests if the next record value is equal to the search text
'if yes then
If (strtext = strname) Then
'assign true to our blnfound variable
blnfound = True
'display the record values on their corresponding controls
NameLabel.Text=DataSet11.Tables("tblNames").Rows(introws).Item("chrfname")
LnameLabel.Text = DataSet11.Tables("tblNames").Rows(introws).Item("chrlname")
End If
'Continue incrementing the record pointer until a match is found
'and the end of file has not been reached
End While
'if the record is not found,  display Record not found in our  messagebox
If blnfound = false Then
MsgBox("Record not found", MsgBoxStyle.Information, "Search a Record")
End If

20. Press F5 to test your application.

21. Try searching names that exists in a database. You can also try searching records that doesn't exist. Notice how our search module works splendidly and effectively. Feels like birthday, right?

22. For future improvements of this module, I suggest adding search options such as search by name or by last name. And I leave that to you to figure out wahaha!

Creating a plain object in DarkGDK

A plain is a mesh object that can be used as ground in your game scene. To create a plain object, use the dbMakeObjectPlain function.

Syntax:

dbMakeObjectPlain(object id,plain width,plain height);

Example:
dbMakeObjectPlain(1,100,100);

By default an object is drawn in gray. You can add colors to your plain object by Using the dbColorObject function which has the following syntax:

dbColorObject(object id, color);

Colors can be defined by using the dbRGB function which has the following syntax:

dbRGB(red,green,blue);

Wherein red, green, and blue are numbers that ranges from 0-255.

The following codes demonstrates dbMakeObjectPlain and dbColorObject at work:

// Dark GDK - The Game Creators - www.thegamecreators.com

// the wizard has created a very simple project that uses Dark GDK
// it contains the basic code for a GDK application

// whenever using Dark GDK you must ensure you include the header file
#include "DarkGDK.h"

// the main entry point for the application is this function
void DarkGDK ( void )
{
// turn on sync rate and set maximum rate to 60 fps
dbSyncOn   ( );
dbSyncRate ( 60 );
//Creates a 400 X 200 plain object with an object id of 1 and 
dbMakeObjectPlain(1,400,200);
//Applies a red color to our plain
dbColorObject(1,dbRGB(255,0,0));
//Positions the camera on the side of our object
dbPositionCamera(-1,-600,-100);
// our main loop
while ( LoopGDK ( ) )
{
// update the screen
dbSync ( );
}
//deletes all objects
for ( int i = 1; i < 50; i++ )
dbDeleteObject ( i );
// return back to windows
return;
}

Accepting Decimal or Floating Point Inputs(Windows Forms Applications-Microsoft Visual C++ 2008 Express Edition)

In general, every data inputted in a textbox are treated as string. For instance if you enter 5, Visual C++ 2008 will treat it as “5” which is a problem if you intend to use the input in calculations. If you have read my post about Accepting Numeric Data, we have used int::Parse function to treat the input as a numeric data. Unfortunately int::Parse works only on whole number inputs and returns a build errors on floating point input. To prepare your variable or control in accepting floating point input use the float::Parse function.

Syntax:
Destination=float::Parse(Source);

Wherein;
1. Source can be a control or variable that where you will be getting your floating point data.
2. Destination is a control or variable will you will be displaying or storing your floating point data.

The following steps demonstrate float::Parse at work:

1. Start MSVC++ Express 2008 by clicking on the Start button, All Programs then clicking on the Microsoft Visual C++ Express Edition Start menu option.

2. Click File>New>Project. The new project dialog box will then come into view.

3. Select Windows Forms Application from the Visual Studio Installed templates, type the project name>Click Ok.
After clicking the Ok button, an IDE suited for windows forms application will then appear containing a form, a toolbox window, and a properties window.

4. Create a user interface similar to the one below:



Note: Those texts that appear beside each control are the suggested names for our form controls in this example. If you noticed I am using .Net naming convention in naming controls because it is simpler to use than Leszynski naming convention. To change the value of the name property of each control, just click each individual control then locate the name property in the properties window then assign those descriptive names in our illustration correspondingly.

5. Double-click your form then locate the following line:

#pragma endregion

6. Declare the following variables below it:

float fltcurrpricex,fltcurrpricey, fltdiscountx,fltdiscounty, fltnewpricex,fltnewpricey;

Declaring these variables below the #pragma endregion line allows our variables to be available publicly and to be used by other procedures.

Your code should now appear just like this:

#pragma endregion  
float fltcurrpricex,fltcurrpricey, fltdiscountx,fltdiscounty, fltnewpricex,fltnewpricey;  

7. Double-click the control named ComputeButton,type the following:

fltcurrpricex=float::Parse(this->XPricetextBox->Text);
fltcurrpricey=float::Parse(this->YPricetextBox->Text);
fltdiscountx=float::Parse(this->DiscountXtextBox->Text);
fltdiscounty=float::Parse(this->DiscountYtextBox->Text);
fltnewpricex= fltcurrpricex - (fltcurrpricex*fltdiscountx);
fltnewpricey= fltcurrpricey - (fltcurrpricey*fltdiscounty);
this->XPricelabel->Text=Convert::ToString(fltnewpricex);
this->YPricelabel->Text=Convert::ToString(fltnewpricey);

8. Your could willnow look like this:

private: System::Void ComputeButton_Click(System::Object^  sender, System::EventArgs^  e) 
{
fltcurrpricex=float::Parse(this->XPricetextBox->Text);
fltcurrpricey=float::Parse(this->YPricetextBox->Text);
fltdiscountx=float::Parse(this->DiscountXtextBox->Text);
fltdiscounty=float::Parse(this->DiscountYtextBox->Text);
fltnewpricex= fltcurrpricex - (fltcurrpricex*fltdiscountx);
fltnewpricey= fltcurrpricey - (fltcurrpricey*fltdiscounty);
this->XPricelabel->Text=Convert::ToString(fltnewpricex);
this->YPricelabel->Text=Convert::ToString(fltnewpricey);
}

9.Press F5 to test your appliaction.

Storing and retrieving an image from a database file
(Visual Basic 2008 Express Edition)

One of the frequent problems encountered by most newbie database developers and designers is the difficulty in storing or retrieving an image data from a database file. Though there are a number of ways to store an image, the most comfortable way (for me) is to create a fieldname and store the URL (Uniform Resource Locator) or location and filename of an image as its value. One of the advantages of this approach is it allows you to access an image from a database file painlessly and swiftly compare to using ole objects. Prior to the image retrieval process, I want you to make a database file named “dbicon” containing a table named “tblicons” . This table will store the name and icon of a particular application. Use the following specifications:

Field Name
Data Type
Description
chrdesc
Text
This will store the name or descriptionof an application
chrimage
Text
This will store the icon of an application.I suggest that you use the maximum value for this field which is 255 because most image URLs contain multiple characters. Alternatively, you can use the memo data type.

To retrieve the image from the database file and display it into a picture box on your client application, use the ImageLocation property of the picture box then assign the value of your image fieldname as the ImageLocation’s value.

After designing the structure of your table, you can enter appropriate values for each field. For instance:

Chrdesc
chrimage
Apache Web Server
C:\Program Files\Apache Group\Apache\manual\images\favicon.ico
PHP
C:\Program Files\PHP\php.gif


Now that you are done designing your table, it’s time to retrieve the image from your database file and display it in a picture box on your client application. To achieve this, the idea is to make use of the ImageLocation property of the Picturebox and assign the value of your image fieldname to it. The following steps demonstrate how:

1. Click Start>Select All Programs then Click Visual Basic 2008 Express Edition. The Visual Basic 2008 Express Edition IDE should then appear.

2. Click the File menu then Select New Project.

3. The New Project dialog box should then come into view >Double-click Windows Forms Application from the available templates.

4. A new form will appear. Before adding appropriate controls to our form let us first establish a connection to our dbicons database file. To do this we will use a database access tool called OleDbDataAdapter. OleDbDataAdapter will enable us to set the filename of a database file and the name of the table that we wanted to be made available in our project. It also permits us to set-up how the record values will be displayed on our form by using an appropriate SQL statement.

5. By default, OleDbDataAdapter is not shown on the VB 2008 control toolbox, to add it, click Tools>Choose control toolbox>Type “ole” (no quotes ) on the filter textbox then check all the items that starts with “ole” and finally click the Ok button. OleDbDataAdapter should now appear on your toolbox.

6. Expand the All Windows Forms toolbox category then double-click OleDbDataAdapter.

7. A Data Adapter configuration wizard will then appear. Click the new connection button>Select Microsoft Access Database File from the data source list.

8. Click the browse button then locate your dbicons.mdb file then click the Ok button.

9. Click Next>A message box containing the following prompt will appear:
“The connection you selected uses a local data file that is not in the current project would you like to your project for the connection? If you copy the data file to your project, it will be copied to the project’s output directory”> just click the Ok button then click next.

10. A Generate SQL statement, type “SELECT * FROM tblicons” (no quotes) this will export all the record value of our table to our project then. Click Next after typing the SQL statement and finally click the Finish Button.

11. After specifying the table name, right-click OleDbDataAdapter1 from the bottom portion of VB 2008 IDE then click Generate Data Set then click the Ok button. If you are wondering what a dataset is, a Dataset is an imaginary box the holds the field names of your table. It is use a temporary storage box for table data.

12. At this point, you will need to design the interface of your application. Double-click the label tool. In the properties window, change its text to “Name:” (no quotes).

13. Double-click the textbox tool and put it in the right-side of your label. Change its name to Nametextbox.

14. Add another label and change its text property to “Icon” (no quotes).

15. Add a PictureBox and Position it below the Icon label. Change its name to IconPictureBox .

16. Now, double-click your form, the load procedure event should then come into view:

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    
End Sub
End Class

17. Type the following codes between the Private Sub and End Sub:

'This will fill our dataset with record 
'values specified in our OleDbDataAdapter1
OleDbDataAdapter1.Fill(DataSet11)
'Displays the first record of the 
'first fieldname from our tblicons     table
NameTextBox.Text =DataSet11.Tables("tblicons").Rows(0).Item("chrname")
'Extract the URL of our image stored 
'on the first record value of our   chrimage field and
'store it as a value of our picturebox ImageLocation property
PictureBox1.ImageLocation =DataSet11.Tables("tblicons").Rows(0).Item("chrimage")
18. Your code will now look like this:

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'This will fill our dataset with 
'record values specified in our OleDbDataAdapter1
   OleDbDataAdapter1.Fill(DataSet11)
'Displays the first record of the 
'first fieldname from our tblicons table
NameTextBox.Text = DataSet11.Tables("tblicons").Rows(0).Item("chrname")
'Extract the URL of our image stored 
'on the first record value of our   chrimage field and
'store it as a value of our 
'picturebox ImageLocation property
   PictureBox1.ImageLocation = DataSet11.Tables("tblicons").Rows(0).Item("chrimage")

    End Sub
End Class

18. Press F5 to see the culmination of your effort.

19. You should now see “Apache” beside the Name label and a quill icon beside the Icon label.