Skip to content

Build a currency converter application using WPF in C# with Database

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

In this article, you will learn how to create the “Currency Converter” application using WPF in C# with a database. In the previous article, I have shown you how to build a Currency converter using the static data. Now I will show you to build it using a database. So, let’s start.

NOTE: In the previous article, “Build a currency converter application using WPF in C# with static data,” You have learned everything about the currency converter application and “What is WPF?” etc. Check out the “Build a currency converter application using WPF in C# with static data article to have a clear idea about this article if you are new to this article.

Technical Requirements

In terms of technical requirement as you are already familiar with the C# Programming Language and IDE (Visual Studio). Now for building the same application using a database you need to know about the Basics of SQL.

Basic Knowledge of SQL

SQL stands for the Structured Query Language. It is used to communicate with a database.

Standard SQL commands such as “Create,” “Insert,” “Update,” “Delete,” “Drop,” and “Select” will be used to accomplish almost everything that one needs to do with a database.

Step by step guide for building a Currency Converter application using WPF and C# with Database

In the previous article, you have done almost similar steps. Although, I want you to create a new project instead of making the previous project more complex.

Create a new project

  • Firstly, open Visual Studio and select Create a new project under the Get started menu.
  • Select WPF App (.Net Framework)
  • Click on next button.

Configure project

  • Enter the project name as you wish. I am using the naming the project as CurrencyConverter_Database.
  • Choose the location where you want to save your project.
  • Click on the create button.

As you have completed the project creation steps, the Visual Studio creates the project with some default pages.

  • MainWindow.xaml
  • MainWindow.xaml.cs
  • App.xaml
  • App.config

I have already explained the above files in the previous article,  “Build a currency converter application using WPF in C# with static data.

  • The default code generated in MainWindow.xaml

Designing the application

Now, change the following properties in the XAML code for the NavigationWindow element:

  • First, set the Title property value to “Currency Converter.”
  • Remove default Height and Width from window tag properties and add SizeToContent=” WidthAndHeight” property to set window form according to the content size.
  • Set up WindowStartupLocation property to “CenterScreen” to set the center position of the window.
  • Set up Icon=”Images\money.png” property to set the application’s icon and so will be visible on the title bar.

After making the above changes, the property will look as below

  • The WPF TabControl is usually positioned on the top of the controller, which allows you to access by clicking on the tab header and also split your interface up into different areas. Tab controls are commonly used in windows applications.
  • Each tab represents a TabItem element, where the header property controls the text shown on it. You may define an element inside of it that will be shown if the tab is active.

Now, let’s start designing currency converter tab

  • Add below code between the <TabItem Name=”tbConverter” Header=”Currency Converter”></TabItem>  tag.
  • The Grid Panel provides a flexible area which consists of rows and columns also child elements can be arranged in tabular form. The items can be added to any specific row and column by using Grid.Row and Grid.Column properties.
  • By default, the Grid panel is created with one row and one column. And, the Multiple rows and columns are created by RowDefinitions and ColumnDefinitions properties.

I have explained to you about the usage of Border and StackPanel in WPF. If you haven’t checked out, please check out in the previous article,  “Build a currency converter application using WPF in C# with static data.

Add the Border code as below:

  • Add the Border code as below:

App.xaml page

Let’s start designing a currency master tab

Before moving further, let’s understand DataGrid control.

The DataGrid control enables you to edit and display data from many sources, such as from a SQL database, or any other bindable data source.

DataGrid columns can display text, controls, such as a ComboBox, or any other WPF content, such as buttons, images, or any content contained in a template. We can use a “DataGridTemplateColumn” to display data defined in a template.

DataGrid can be customized in appearance, such as color, size, and cell font. It supports all templating functionality and styling of other WPF controls. It also includes default and customizable behaviors for sorting, editing, and validation.

MainWindow.xaml final code will look like below:

Output: Currency Converter Tab

Output: Currency Master Tab

Add local SQL Database in Application

The database that is accessed through a server is called a service-based database. It uses an MDF data file, which is the SQL Server format. For connecting the SQL Server database, the SQL Server service must be running because it processes your requests and access the data file.

A local database is a database that can be used locally on a computer. It doesn’t require a server. The advantage of using a local database is that you can easily migrate your project from one computer system to another (you don’t need to setup/configure a database server). Microsoft provides a local database within the visual studio, often called SQLCE (CE stands for compact edition).

A local database is essential for developing small scale C# applications because it doesn’t require a server to store it.

Follow steps for create a local database:

  • Open solution explorer.
  • Right-click on the application name. Select Add >> New Folder
  • Set folder name Database.
  • Right-click on Database folder select Add >> New Item
  • Select a service-based database under the data menu. Set the name of the database CurrencyConverter. Database extension is .mdf.
  • Click on the add button.
  • After clicking on the add button, our database is created and shown in solution explorer under the database folder.
  • The database can open by double-clicking in the Server Explorer, which roughly corresponds to the SQL Server Management Studio.

Add table:

  • Right-click on Tables-> Add New Table, a new table created with an ID field as a template.
  • The window splits into two-part:
    • Design
    • T-SQL
  • T-SQL script generates automatically.

In this table, add three columns: 

  • Id – Id column is a primary key with int datatype and set identity (1,1).
    • A Primary Key: A primary key constraint used to uniquely identify each record in a table. The Primary keys must contain cannot contain NULL values and it should be UNIQUE values. At a time table can have only one primary key.
    • Identity: The “Identity(seed, increment)” and seed is the value of the first row loaded into the table. Default value of seed and increment is one, i.e. (1,1). Increment is the incremental value added to the identity value of the previous row. 
  • Amount – The amount column used for store currency value and its data type is float.
  • CurrencyName – this column used for store currency name with nvarchar(50) datatype.

After that, add below T-SQL syntax click on the update button the changes saved with an update button in the menu area.

T-SQL Syntax:-

The name of a table is entered in the script below:

If you subsequently rename the table in the script, a completely new table will be created as a copy.

Adding a connection string to the database

The connection to the database can be found by opening the database >> properties and taking the values ​​under connection string. In this example, the data source shows local DB with the file path now copy connection string.

Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Hp\source\repos\CurrencyConverter_Database\Database\CurrencyConverter.mdf;Integrated Security=True

Open App.config file from solution explorer. Add connection string between <configuration></configuration> tag. Like in the code below.

In the connection string:

  • Data Source: It identifies the server name, which could be the IP address, machine domain name or the local machine.
  • Initial Catalog: It identifies the database name.
  • Integrated Security: Using the Windows authentication, it specifies Integrated Security=”True” in the connection string and database authentication login with server authentication. It specifies Integrated Security=”false” in the connection string.
  • User Id: Name of the user configured in the SQL server.
  • Password: Password matching SQL server user id.

Now, add the connection string and save the App.config file

Main part of the application

  • The default code added in MainWindow.xaml.cs

The namespace is designed to provide a way to keep one set of names separate from another. This class names declared in one namespace does not conflict with the same class names declared in another.

The namespace definition begins with the keyword namespace.

It is a partial class is a special feature of C# which provides a special ability to implement the functionality of a single class into multiple files. When the application is compiled all the files are combined into a single class file.

The partial class is created by using a partial keyword and the keyword is also useful to split the functionality of interfaces, methods, or structure into multiple files.

InitializeComponent() is a method automatically written for you by the Form Designer when you create/change your forms. Now you need to drag controls to the Form in Visual Studio. Behind the scenes, Visual Studio adds code to the InitializeComponent method, which is called in the Form constructor.

Remove unnecessary namespace from our code.

  • Create an object for SQL connection, SQL command, and SQL DataAdapter. Before working with the database, you must import a data provider namespace, by placing the following at the beginning of your code module using System.Data.SqlClient. As shown in the code below:

A SqlConnection object represents a unique session to an SQL server data source. With a client/server database system, it is equivalent to a network connection to the server. SQL connection is used with a SQL data adapter and SQL command to increase performance when connecting to a Microsoft SQL server database.

Create a mycon() method. We can use the SQL connection class to establish a connection with a SQL server database.

  • Add using system namespace. The using System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.

To use ConfigurationManager class, add reference system.configuration.

  • Open solution explorer. Right-click on references. Click on Add Reference find system.configuration check the checkbox and click on the OK button.
  • Our MainWindow.xaml.cs page add namespace using System.Configuration on top of the page.
  • con.Open() Method opens a database connection with the property settings specified by the ConnectionString.

Bind Currency From and To Combobox

Create a private method as BindCurrency().

Private is an access modifier. Type or member can be accessed only by code in the same class or struct.

The Void keyword is used for the method signatures to declare a method that does not return any value. The method declared with the void return type cannot provide any arguments to any return statements they contain.

The BindCurrency() is a name of method.

  • Add the mycon() method of connecting with the database and open database connection.
  • To use DataTable, add the namespace using System.Data.
  • A DataTable object represents tabular data as an in-memory, tabular cache of rows, columns, and constraints.
  • DataTable dt = new DataTable(); Using this code you are creating an empty data table for which the TableName property is set to dt. You can use this property to access this data table from a DataTable Collection.
  • cmd = new SqlCommand() A SqlCommand object allows you to query and send commands to a database. It has methods that are specialized for different commands. Between the opening and closing bracket (), add SQL query in double-quotes.
  • cmd.CommandType decides what type of object a command will execute.
  • da = new SqlDataAdapter(cmd) In this DataAdapter constructor, shown in the following code, will accept a parameter that contains the command text of the object’s select command property.
  • da.Fill(dt) The DataAdapter serves as a bridge between a DataSet and a data source to retrieve and save data.
  • DataRow class provides the functionality to add a new row i.e., new record into the data table. Datarow object inherits the schema of the asp.net data table. It allows you to add the values for each data column according to the specified data type for a data column of the data table.
  • Using the below code, we insert one record in our data table. This record is set as default in our Combobox.
  • Assign data table data to Combobox using ItemSource property.
  • Set Combobox DisplayMemberPath property, which you want to show in Combobox as display text. Here we use currency name as display text.
  • Set Combobox SelectedValuePath property, which you want to set in Combobox as value. Id use as our value member.
  • Make sure both properties are set with the same DataTable column name.
  • After add BindCurrency() method call it in MainWindow() method. because when program run MainWindow() method is call first.

Output:– In Combobox no currency names are shown because we didn’t add any currency in our database table.

  • Create new method for Clearcontrols().
  • This method is used to clear all control data which the user entered.
  • Add this method in MainWindow() method.
  • Create a method NumberValidationTextBox() this method is used for Amount textbox to allow the only number using Regular Expression.
  • For use Regular Expression add using System.Text.RegularExpressions namespace.
  • For TextCompositionEventArgs add using System.Windows.Input namespace. This namespace is use for input controls e.g. Textbox.
  • Create the new method – ClearMaster().
  • This method is used to clear all control data which the user entered.
  • Assign the save button click event.
  • Add the try-catch block. A try-catch block placed around code that could throw an exception. If an exception is thrown, this try-catch block will handle the exception to ensure that the application does not cause an unhandled exception, user error, or crash.
  • Check validation for the amount textbox. If the amount textbox is blank, then it will show the message “Please enter amount.”
  • Check validation for the currency name. If the currency name textbox is blank, it will show the message “Please enter currency name.”
  • Click on the Save button if the amount textbox and currency name textbox are not blank then show confirmation message “Are you sure you want to save ?”.
  • Click on the “yes” button then start operation for save.
  • Call mycon() method for database connection and open database connection.
  • cmd = new SqlCommand() write a query to insert data in the table between opening and closing bracket.
  • Use AddWithValue whenever you want to add a parameter by specifying its name and value. The “txtAmount.Text” value store in @Amount parameter and @Amount parameter is used as a value in our insert query.
  • ExecuteNonQuery is used for executing queries that do not return any data. It is used to execute the SQL statements like an update, insert, delete, etc.

Bind Datagrid:

Edit and Delete Code:

  • Create a Datagrid selected cell changed event. To edit and delete.
  • Create an object for Datagrid. Using “DataGrid grd = (DataGrid)sender”. The grd is an object name.
  • The DataRowView objects expose values as object arrays indexed by either the name or the column’s ordinal reference in the underlying table. You can access the DataRow that is presented by the DataRowView by using the Row property of the DataRowView.
  • Select the DataRowView to identify the selected row records.
  • The Id column is not shown in Datagrid because its visible property is set as false. But it exists in Datagrid.
  • Now, extract the id from selected DataRowView and assign it to CurrencyId variable, which will be used to update the records.
  • We need to check the if(grd.SelectedCells[0].Column.DisplayIndex == 0) to edit the records. We can get the amount and currency name to edit once the condition gets it is true.
  • We need to check the if (grd.SelectedCells[0].Column.DisplayIndex == 1) for delete the records. Once the condition gets true, it will show the confirmation message, “Are you sure you want to delete?”. If you click on the “yes” button, then delete query fire and delete record in the table using id.
  • After completing the delete, the message “Data deleted successfully” will be shown. 
  • CommandType can be one of the following values: Text, StoredProcedure, TableDirect. The property CommandText should contain the text of a query that must be run on the server when the value is CommandType. StoredProcedure, CommandText property must be the name of a procedure to execute.

Update button code:

  • Click on the edit button to update the amount and the currency name in the textbox. Fill the textbox with this value and click the save button. The text changed save to update.
  • Update the button code, add in save button click event.
  • Need to check the condition whether CurrencyId is not equal zero and greater than zero before displaying the confirmation dialogue to update the record.
  • The record will be updated once the above condition is matched, and the update query gets executed. Please see below the code snippet.

Create a cancel button click event:

From currency Combobox selection changed event:

  •  SelectionChanged Event is issued when the Combobox changes the currently selected item.
  • If the user chooses the same item as the item is currently being selected, then the selection is not changed, and therefore this event will not be triggered.
  • Check the condition if cmbFromCurrency.SelectedValue not equal to null and cmbFromCurrency.SelectedValue not equal to zero
  • Set from currency Combobox selected value in CurrencyFromId variable.
  • Execute select command which fetches amount from Currency_Master table using Id.

To currency Combobox selection changed event:

From currency and to currency Combobox preview key down events:

  • The previewkeydown event is used to identify which key to press on the keyboard.
  • Here I am using the tab and enter key if the user press tab or enter key, then the selection changed event execute.

Calculation of Currency Converter:

Create a convert button click event. Then click on the convert button this event fire.

  • Declare a variable ConvertedValue with the double datatype. It is used for store converted value and shown in the label.
  • Check validation if the Amount textbox is blank, then it shows the message “please enter amount.”
  • Check validation if the user does not select any currency from FromCurrency Combobox, then it shows the message “Please select currency from.”
  • Check validation if the user does not select any currency from ToCurrency Combobox, then it shows the message “Please select currency to.”
  • Check condition if from currency and to currency select the same currency name then stores amount textbox value in converted value variable. e.g., Enter in Amount textbox ten, then Select from currency Combobox USD, and to currency Combobox USD, then show currency name with a converted value like “USD 10.000.”
  • If From currency and To currency is not the same, then else part will execute.
  • From Currency Value Multiply(*) with Amont Textbox Value and then That Total Divided(/) with To Currency Value and its store in ConvertedValue variable.
  • Display in Label Converted Currency name with ConvertedValue.
  • Create a clear button click event.
  • Call ClearControls() method for clear all controls input which user entered.

Final code of MainWindow.xaml.cs

Output:

Insert currency amount and currency name:

Edit and update record:

Delete record:

Convert currency From and To currency same:

From and To currency is different:

Summary

In this article, you have learned how to create a Currency Converter in WPF using C#. Here, you have used the database to store a currency name and currency amount and perform the crud operation on it.

 

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide