Translate Page in your Language

Build a sample Dictionary application

Build a sample Dictionary application

In this C SHARP sample program, you will learn to build a simple dictionary. The key terms are English words and each of English word is translated in to Balochi language when the word is selected from the list or when it is typed in to the search box. The word that is typed in the search textbox is searched through the list. If it is found, the word will be selected in the list and its translation will display in a right-hand rich text box. We use Microsoft Access 2007 database to store the English words and their translations. When the dictionary form first loads, the English words will be retrieve from the database file and populated in to a list box.
Build Simple dictionary
Now, you understand overall idea of project. Lets move to the interface design phase. To complete this phase you need to follow the steps below:
-Open Visual Studio 2008 and create a new project by going to
 File menu-->select New and click on Project...
-The New Project dialogue opens.
-In the New Project dialogue, under Project Types select Visual C#, and select Windows Form Application under Tamplates. In the Name box type EnglishBalochiDictionary.
new project name
-You can click Browser you choose the location to store your project files.
-Click Ok. Then you will see a default form named Form1.
new form
-Right-Click on the form and select properties to display the properties window of the form.
change properties value
-On the Property Manager tab. You will need to set the
 Text property to EngBalochi and the Name property to Dic. 
-Set the form Backcolor property to Inactivecaption.
-Set the form FormBorderStyle property to FixedDialog to make the form borders unresizable.
-Expand the Toolbox on the left side to display a list of Visual Basic controls and components.
design dictionary form
-Drag and drop one ListBox on to the form.
-Rename the list box by setting its Name property to Lstterms.
-Drag and drop one Textbox on the form above the list box.
Then drag and drop one RichTextbox to the right of the list box. You need to set the Name property of the textbox to Txtbox, and set the Name property of the rich text box to Txtresult. The fore color of the rich textbox is set to MenuHighlight by using the its Forecolor property. Its ReadOnly property is also set to True. This will not allow users to edit the text in the rich text box.
-To add a menu to the form, you need to drag and drop MenuScript from the Toolbox.
insert menu
-Type &File in The Type Here box and in the next Type Here type &Help.
-Type &Close in to the Type Here box under the File menu and type &About... in to the Type Here box under the Help menu.
Now we finish the interface design of our simple dictionary. Then we will move to Create Database phase.

Create a Microsoft Access 2007 database

As you already knew, to store the English key terms and their EnglishBalochi translations, we need a Microsoft Access 2007 database. Now lets create a database called "data.accdb" in Microsoft Access 2007 and save it in the "bin/debug" directory of your project.
This database has one table called Tblterms that has only two fields--Enterm and Balochi.
The sample data is entered to each field as shown below:
database table
After you create a database and enter some sample data, you can move to Create connection and populate data in the list phase.
The code below will help you to connect to the database file and retrieve data to put in the Lstterm listbox:
-Double-click on the form to open the code window
-You will see the code as shown below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EnglishBalochiDictionary
{
    public partial class Dic : Form
    {
        

        public Dic()
        {
            InitializeComponent();
        }
private void Dic_Load(object sender, EventArgs e)
        {
}
}
}
You need to add the statement Using System.Data.OleDb; to the Using group statements in the code above. So it will be come:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace EnglishBalochiDictionary
{
    public partial class Dic : Form
    {
        

        public Dic()
        {
            InitializeComponent();
        }
private void Dic_Load(object sender, EventArgs e)
        {
}
}
}
-Under the "public partial class Dic: Form" line type the following code:
         private OleDbConnection cn;
        private OleDbDataReader reader;
        private OleDbCommand com;
        private DataSet rs;
        private OleDbDataAdapter ad;
This code will declare
cn variable as the OleDbConnection class, 
reader variable as OleDbReader class, 
com variable as OleDbReader Class, 
rs variable as DatSet class, and 
ad as OleDbDataAdapter classs. 
These variables will be used to create their objects of their types.
-Create a method to connect with DataBae by typing the code as shown below:
private void Dic_Load(object sender, EventArgs e)
        {
          
            rs = new data3DataSet();
            string constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data3.mdb";
            cn = new OleDbConnection(constring);
            cn.Open();
            ad = new OleDbDataAdapter("SELECT * FROM Tblterms ORDER By Enterm", cn);
            ad.Fill(rs, "Tblterms");
            com = new OleDbCommand("SELECT Enterm From Tblterms ORDER BY Enterm", cn);
            reader = com.ExecuteReader();
//clear list
            Lstterms.Items.Clear();
            //Lstterms.DataSource = reader;

            //clear txtresult
            Txtresult.Text = "";

            while (reader.Read())
            {
 
                Lstterms.Items.Add(reader[0].ToString());
            }
// list.Clear();
            TxtBox.Focus();
        }
The code starts by create a DataSet object to store the table got from the database and a connection object to connect to the database file: to get database address to connect database follow the below steps
add new data source
//connect to database
From Menu Click Data then from submenu select Add New Data Source
Menu-->Data --> Add New Data Source --> 


data source configuration wizard
Data Source Configuration Wizard appeared
Select Database then click Next
Database --> Next
Choose New Connection appearing Add Connection
add connection
From Data Source select Microsoft Access Database File (OLE DB) and for Database file name area click Browse Button and then from Directory select Microsoft Access Database File that you are created before.
Click Test Connection Button.
test connection
If you get information Test Connection succeeded then press Ok Button.
connection string
click on (+) connection string, appearing connection string.
Copy and Past connection string
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\bin\Debug\data.accdb
rs = new DataSet();
            string constring = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source=data.accdb";
            cn = new OleDbConnection(constring);
            cn.Open();

The Adapter object is created to get data from the Tblterms table and
the data is filled to the DataSet object rs by using the Fill() method of the adapter:
ad = new OleDbDataAdapter("SELECT * FROM Tblterms ORDER By Enterm", cn);
            ad.Fill(rs, "Tblterms");
The Command object com is also created to get data from the table and populate the list box:
com = new OleDbCommand("SELECT Enterm From Tblterms ORDER BY Enterm", cn);
          reader = com.ExecuteReader();
//clear list
            Lstterms.Items.Clear();

            //clear txtresult
            Txtresult.Text = "";

            while (reader.Read())
            {
              Lstterms.Items.Add(reader[0].ToString());
            }
The search text box is set the focus to make sure that the cursor is active in this box for text input.
Txtbox.Focus();
By putting the method connection in the form load event, the list box Lstterms will be populated by the English words:
Now you have data filled in the list box Lstterms when the form loads. The next phase is to write some C# code to create a workable search text box.
To make the search box workable you need the following code that is applied to the TextChanged event of the text box:
private void TxtBox_TextChanged(object sender, EventArgs e)
        {
            
            int index = Lstterms.FindString(this.TxtBox.Text);
            
                if(0 <= index)
                {
                    Lstterms.SelectedIndex = index;
                  
                    
            }
  }
  
When a user types a word in the search text box TxtBox, This word is used to compare with a word in the list box. If the words are matched the word in the list will be selected and its translation will display in the rich text box Txtresult.
If the use chooses to select from the list rather than typing in to the search box, you need another piece of code applied to the SelectedIndexChanged event of the list box:
private void Lstterms_SelectedIndexChanged(object sender, EventArgs e)
        {
           DataRow dr;
            dr = rs.Tables[0].Rows[Lstterms.SelectedIndex];
            Txtresult.Clear();   //clear result
           Txtresult.Text = dr[1].ToString().Trim();
           
            
        }
  
//If the user chooses to Click the list rather than typing in to the search box, you need another piece of code applied to the Lstterms_MouseDown event of the list box:
private void Lstterms_MouseDown(object sender, MouseEventArgs e)
        {
            DataRow dr;
            dr = rs.Tables[0].Rows[Lstterms.SelectedIndex];
            Txtresult.Clear();   //clear result
            Txtresult.Text = dr[1].ToString().Trim();
            
            TxtBox.Text = dr[0].ToString().Trim();
        }
Note: The DataRow dr is used to get data of a selected row of the table.

Make the form smarter

Now if you maximize the form, the items are not smart enough to fit the form. What we want to talk in this page is to help you create a form that its items still stay fit with the form when it is resized for maximum state. To accomplish this task you need the following code that is applied to the Resize event of the form:
private void Dic_Resize(object sender, EventArgs e) 
         {
             if (this.WindowState == FormWindowState.Maximized)
             {
                 Lstterms.Height = this.Height;
                 Txtresult.Height = this.Height;
                 Txtresult.Width = this.Width;
             }
        }
  
Note: If you try to resize the form and the code doesn't do its job you need to add another line of code(as shown below) to the form load event:
private void Dic_Load(object sender, EventArgs e)
        {
.
.
.
.
            

            this.Resize += new EventHandler(Dic_Resize);
          

 // list.Clear();
            TxtBox.Focus();
        }
  
When the form loads many objects such as cn, rs, ad, com,and reader, are also created in the program for uses and these objects occupy spaces in computer memory. When the form is closed these objects should be released from the memory.
private void Dic_FormClosed(object sender, EventArgs e)
        {
            cn.Close();
            cn = null;
            com = null;
            reader = null;
            ad = null;
            rs = null;
            
        }
  
You also need to add code:
   this.FormClosed += new FormClosedEventHandler(Dic_FormClosed);
   
to the form load event to make Dic_FormClosed() method callable.
private void Dic_Load(object sender, EventArgs e)
        {
.
.
.
.
            

            this.Resize += new EventHandler(Dic_Resize);
            this.FormClosed += new FormClosedEventHandler(Dic_FormClosed);
          

 // list.Clear();
            TxtBox.Focus();
        }
Another thing we want to talk here is to let the user close the program when his/her clicks on the Close sub menu item form the File menu. This task can be done simply by attaching the following code to the click event of the Close sub menu item:
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
       }
Now, let Run your program.......

Google+ Followers