Skip to content

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

Become a developer with our complete learning paths
Become a developer with our complete 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
<Window x:Class="CurrencyConverter_Database.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CurrencyConverter_Database"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        
    </Grid>
</Window>

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

<Window x:Class="CurrencyConverter_Database.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CurrencyConverter_Database"
        mc:Ignorable="d"
        Title="Currency Converter" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" Icon="Images\money.png">
    <Grid>
        
    </Grid>
</Window>
  • 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.
<TabControl Name="tbMain" TabStripPlacement="Top">

    <TabItem Name="tbConverter" Header="Currency Converter"></TabItem>

    <TabItem Name="tbMaster" Header="Currency Master"></TabItem>

</TabControl>

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.
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="60"></RowDefinition>
        <RowDefinition Height="80"></RowDefinition>
        <RowDefinition Height="150"></RowDefinition>
        <RowDefinition Height="100"></RowDefinition>
        <RowDefinition Height="150"></RowDefinition>
    </Grid.RowDefinitions>
</Grid>

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:

<Border Grid.Row="2" Width="800" CornerRadius="10" BorderThickness="5" Margin="100,0">
    <Border.BorderBrush>
        <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
            <GradientStop Color="#ec2075" Offset="0.0" />
            <GradientStop Color="#f33944" Offset="0.50" />
        </LinearGradientBrush>
    </Border.BorderBrush>
    <Rectangle Grid.Row="2">
        <Rectangle.Fill>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                <GradientStop Color="#ec2075" Offset="0.0" />
                <GradientStop Color="#f33944" Offset="0.50" />
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>
</Border>
  • Add the Border code as below:
<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" Height="50" Width="1000" VerticalAlignment="Center" Margin="0,5">
    <Label Height="50" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Currency Converter" FontSize="25" Foreground="#ec2075" FontWeight="Bold"></Label>
</StackPanel>

<StackPanel Grid.Row="1" Orientation="Vertical" HorizontalAlignment="Center" Height="80" Width="1000">
    <Label Height="40" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Converted Currency" FontSize="20"></Label>
    <Label Name="lblCurrency" Height="40" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="20"></Label>
</StackPanel>

<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Height="60" Width="800" Margin="100,0">
    <Label Height="40" Width="150" Content="Enter Amount : " Margin="35 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
    <Label Height="40" Width="150" Content="From : " Margin="110 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
    <Label Height="40" Width="150" Content="To : " Margin="130 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
</StackPanel>

<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" Height="90" Width="800" VerticalAlignment="Bottom" Margin="100,0">
    <TextBox Name="txtCurrency" Width="200" Height="30" Margin="40 0 0 0" PreviewTextInput="NumberValidationTextBox" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top"></TextBox>
    <ComboBox Name="cmbFromCurrency" Width="170" Height="30" Margin="60 0 40 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" SelectionChanged="cmbFromCurrency_SelectionChanged" PreviewKeyDown="cmbFromCurrency_PreviewKeyDown" MaxDropDownHeight="150"></ComboBox>
    <fa:ImageAwesome Icon="Exchange" Height="30" Width="30" Foreground="White" VerticalAlignment="Top"></fa:ImageAwesome>
    <ComboBox Name="cmbToCurrency" Width="170" Height="30" Margin="40 0 0 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" SelectionChanged="cmbToCurrency_SelectionChanged" PreviewKeyDown="cmbToCurrency_PreviewKeyDown" MaxDropDownHeight="150"></ComboBox>
</StackPanel>

<StackPanel Grid.Row="3" Height="100" Width="1000" Orientation="Horizontal">
    <Button Name="Convert" Height="40" Width="150" Content="Convert" Click="Convert_Click" Margin="350 0 20 0" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
        <Button.Background>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                <GradientStop Color="#ec2075" Offset="0.0"/>
                <GradientStop Color="#f33944" Offset="0.5"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
    <Button Name="Clear" Height="40" Width="150" Content="Clear" Click="Clear_Click" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
        <Button.Background>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                <GradientStop Color="#ec2075" Offset="0.0"/>
                <GradientStop Color="#f33944" Offset="0.5"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
</StackPanel>

<StackPanel Grid.Row="4" Height="150" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
    <Image Height="150" Width="150" Source="Images\Logo.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="325 0"/>
</StackPanel>

App.xaml page

<Style x:Key="ButtonRound" TargetType="Button">

    <Setter Property="Background" Value="AliceBlue"></Setter>

    <Setter Property="Foreground" Value="White"></Setter>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="5" Background="{TemplateBinding Background}" BorderThickness="0.5">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

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.

<TabItem Name="tbMaster" Header="Currency Master">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60"></RowDefinition>
            <RowDefinition Height="100"></RowDefinition>
            <RowDefinition Height="60"></RowDefinition>
            <RowDefinition Height="200"></RowDefinition>
            <RowDefinition Height="150"></RowDefinition>
        </Grid.RowDefinitions>
        <Border Grid.Row="1" Width="800" CornerRadius="10" BorderThickness="5" Margin="100,0">
            <Border.BorderBrush>
                <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                    <GradientStop Color="#ec2075" Offset="0.0" />
                    <GradientStop Color="#f33944" Offset="0.50" />
                </LinearGradientBrush>
            </Border.BorderBrush>
            <Rectangle Grid.Row="1">
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="#ec2075" Offset="0.0" />
                        <GradientStop Color="#f33944" Offset="0.50" />
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Border>

        <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" Height="50" Width="1000" VerticalAlignment="Center" Margin="0,5">
            <Label Height="50" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Currency Master" FontSize="25" Foreground="#ec2075" FontWeight="Bold"></Label>
        </StackPanel>
        <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Height="40" Width="800" Margin="100,0">
            <Label Height="40" Width="180" Content="Enter Amount : " Margin="180 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
            <Label Height="40" Width="180" Content="Currency Name : " Margin="60 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
        </StackPanel>
        <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Height="60" Width="800" VerticalAlignment="Bottom" Margin="100,0">
            <TextBox Name="txtAmount" Width="200" Height="30" Margin="180 0 0 0" PreviewTextInput="NumberValidationTextBox" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top"></TextBox>
            <TextBox Name="txtCurrencyName" Width="200" Height="30" Margin="40 0 0 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" MaxLength="50" CharacterCasing="Upper"></TextBox>
        </StackPanel>
        <StackPanel Grid.Row="2" Height="60" Width="1000" Orientation="Horizontal">
            <Button Name="btnSave" Height="40" Width="150" Content="Save" Click="btnSave_Click" Margin="350 0 20 0" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
                <Button.Background>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="#ec2075" Offset="0.0"/>
                        <GradientStop Color="#f33944" Offset="0.5"/>
                    </LinearGradientBrush>
                </Button.Background>
            </Button>
            <Button Name="btnCancel" Height="40" Width="150" Content="Cancel" Click="btnCancel_Click" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
                <Button.Background>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="#ec2075" Offset="0.0"/>
                        <GradientStop Color="#f33944" Offset="0.5"/>
                    </LinearGradientBrush>
                </Button.Background>
            </Button>
        </StackPanel>
        <StackPanel Height="200" Width="800" Grid.Row="3" Margin="150,0" VerticalAlignment="Top">
            <DataGrid Name="dgvCurrency" AutoGenerateColumns="False" Height="180" Margin="10" Width="480" Background="Transparent" CanUserAddRows="False" SelectedCellsChanged="dgvCurrency_SelectedCellsChanged" SelectionUnit="Cell" VerticalScrollBarVisibility="Auto">
                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="Id" Header="Id" Width="100" CanUserResize="False" Visibility="Hidden" Binding="{Binding Path=Id}"/>
                    <DataGridTemplateColumn Header="" Width="70" IsReadOnly="True" DisplayIndex="0">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Image Source="Images\edit-button.png" ToolTip="Edit" Width="20" Height="20"  x:Name="Revise"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>

                    <DataGridTemplateColumn Header="" Width="70" IsReadOnly="True" DisplayIndex="1">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Image Source="Images\delete-button.png" ToolTip="Delete" Width="20" Height="20"  x:Name="Delete"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>

                    <DataGridTextColumn x:Name="Amount" Header="Amount" Width="100" CanUserResize="False" CanUserReorder="False" Binding="{Binding Path=Amount}" IsReadOnly="True"/>
                    <DataGridTextColumn x:Name="CurrencyName" Header="Currency Name" Width="*" MinWidth="20" CanUserResize="False" CanUserReorder="False" Binding="{Binding Path=CurrencyName}" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>
        <StackPanel Grid.Row="4" Height="150" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
            <Image Height="150" Width="150" Source="Images\Logo.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="325 0"/>
        </StackPanel>
    </Grid>
</TabItem>

MainWindow.xaml final code will look like below:

<Window x:Class="CurrencyConverter_Database.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CurrencyConverter_Database"
        xmlns:fa="http://schemas.fontawesome.io/icons/"
        mc:Ignorable="d"
        Title="Currency Converter" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" Icon="Images\money.png">
    <TabControl Name="tbMain" TabStripPlacement="Top">
        <TabItem Name="tbConverter" Header="Currency Converter">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="60"></RowDefinition>
                    <RowDefinition Height="80"></RowDefinition>
                    <RowDefinition Height="150"></RowDefinition>
                    <RowDefinition Height="100"></RowDefinition>
                    <RowDefinition Height="150"></RowDefinition>
                </Grid.RowDefinitions>
                <Border Grid.Row="2" Width="800" CornerRadius="10" BorderThickness="5" Margin="100,0">
                    <Border.BorderBrush>
                        <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                            <GradientStop Color="#ec2075" Offset="0.0" />
                            <GradientStop Color="#f33944" Offset="0.50" />
                        </LinearGradientBrush>
                    </Border.BorderBrush>
                    <Rectangle Grid.Row="2">
                        <Rectangle.Fill>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                                <GradientStop Color="#ec2075" Offset="0.0" />
                                <GradientStop Color="#f33944" Offset="0.50" />
                            </LinearGradientBrush>
                        </Rectangle.Fill>
                    </Rectangle>
                </Border>

                <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" Height="50" Width="1000" VerticalAlignment="Center" Margin="0,5">
                    <Label Height="50" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Currency Converter" FontSize="25" Foreground="#ec2075" FontWeight="Bold"></Label>
                </StackPanel>
                <StackPanel Grid.Row="1" Orientation="Vertical" HorizontalAlignment="Center" Height="80" Width="1000">
                    <Label Height="40" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Converted Currency" FontSize="20"></Label>
                    <Label Name="lblCurrency" Height="40" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="20"></Label>
                </StackPanel>
                <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Height="60" Width="800" Margin="100,0">
                    <Label Height="40" Width="150" Content="Enter Amount : " Margin="35 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
                    <Label Height="40" Width="150" Content="From : " Margin="110 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
                    <Label Height="40" Width="150" Content="To : " Margin="130 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
                </StackPanel>
                <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" Height="90" Width="800" VerticalAlignment="Bottom" Margin="100,0">
                    <TextBox Name="txtCurrency" Width="200" Height="30" Margin="40 0 0 0" PreviewTextInput="NumberValidationTextBox" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top"></TextBox>
                    <ComboBox Name="cmbFromCurrency" Width="170" Height="30" Margin="60 0 40 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" SelectionChanged="cmbFromCurrency_SelectionChanged" PreviewKeyDown="cmbFromCurrency_PreviewKeyDown" MaxDropDownHeight="150"></ComboBox>
                    <fa:ImageAwesome Icon="Exchange" Height="30" Width="30" Foreground="White" VerticalAlignment="Top"></fa:ImageAwesome>
                    <ComboBox Name="cmbToCurrency" Width="170" Height="30" Margin="40 0 0 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" SelectionChanged="cmbToCurrency_SelectionChanged" PreviewKeyDown="cmbToCurrency_PreviewKeyDown" MaxDropDownHeight="150"></ComboBox>
                </StackPanel>
                <StackPanel Grid.Row="3" Height="100" Width="1000" Orientation="Horizontal">
                    <Button Name="Convert" Height="40" Width="150" Content="Convert" Click="Convert_Click" Margin="350 0 20 0" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
                        <Button.Background>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                                <GradientStop Color="#ec2075" Offset="0.0"/>
                                <GradientStop Color="#f33944" Offset="0.5"/>
                            </LinearGradientBrush>
                        </Button.Background>
                    </Button>
                    <Button Name="Clear" Height="40" Width="150" Content="Clear" Click="Clear_Click" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
                        <Button.Background>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                                <GradientStop Color="#ec2075" Offset="0.0"/>
                                <GradientStop Color="#f33944" Offset="0.5"/>
                            </LinearGradientBrush>
                        </Button.Background>
                    </Button>
                </StackPanel>
                <StackPanel Grid.Row="4" Height="150" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
                    <Image Height="150" Width="150" Source="Images\Logo.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="325 0"/>
                </StackPanel>
            </Grid>
        </TabItem>

        <TabItem Name="tbMaster" Header="Currency Master">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="60"></RowDefinition>
                    <RowDefinition Height="100"></RowDefinition>
                    <RowDefinition Height="60"></RowDefinition>
                    <RowDefinition Height="200"></RowDefinition>
                    <RowDefinition Height="150"></RowDefinition>
                </Grid.RowDefinitions>
                <Border Grid.Row="1" Width="800" CornerRadius="10" BorderThickness="5" Margin="100,0">
                    <Border.BorderBrush>
                        <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                            <GradientStop Color="#ec2075" Offset="0.0" />
                            <GradientStop Color="#f33944" Offset="0.50" />
                        </LinearGradientBrush>
                    </Border.BorderBrush>
                    <Rectangle Grid.Row="1">
                        <Rectangle.Fill>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                                <GradientStop Color="#ec2075" Offset="0.0" />
                                <GradientStop Color="#f33944" Offset="0.50" />
                            </LinearGradientBrush>
                        </Rectangle.Fill>
                    </Rectangle>
                </Border>

                <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" Height="50" Width="1000" VerticalAlignment="Center" Margin="0,5">
                    <Label Height="50" Width="1000" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="Currency Master" FontSize="25" Foreground="#ec2075" FontWeight="Bold"></Label>
                </StackPanel>
                <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Height="40" Width="800" Margin="100,0">
                    <Label Height="40" Width="180" Content="Enter Amount : " Margin="180 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
                    <Label Height="40" Width="180" Content="Currency Name : " Margin="60 0 0 0" VerticalAlignment="Bottom" Foreground="White" FontSize="20"></Label>
                </StackPanel>
                <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Height="60" Width="800" VerticalAlignment="Bottom" Margin="100,0">
                    <TextBox Name="txtAmount" Width="200" Height="30" Margin="180 0 0 0" PreviewTextInput="NumberValidationTextBox" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top"></TextBox>
                    <TextBox Name="txtCurrencyName" Width="200" Height="30" Margin="40 0 0 0" FontSize="18" VerticalContentAlignment="Center" VerticalAlignment="Top" MaxLength="50" CharacterCasing="Upper"></TextBox>
                </StackPanel>
                <StackPanel Grid.Row="2" Height="60" Width="1000" Orientation="Horizontal">
                    <Button Name="btnSave" Height="40" Width="150" Content="Save" Click="btnSave_Click" Margin="350 0 20 0" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
                        <Button.Background>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                                <GradientStop Color="#ec2075" Offset="0.0"/>
                                <GradientStop Color="#f33944" Offset="0.5"/>
                            </LinearGradientBrush>
                        </Button.Background>
                    </Button>
                    <Button Name="btnCancel" Height="40" Width="150" Content="Cancel" Click="btnCancel_Click" Foreground="White" FontSize="20" Style="{StaticResource ButtonRound}">
                        <Button.Background>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                                <GradientStop Color="#ec2075" Offset="0.0"/>
                                <GradientStop Color="#f33944" Offset="0.5"/>
                            </LinearGradientBrush>
                        </Button.Background>
                    </Button>
                </StackPanel>
                <StackPanel Height="200" Width="800" Grid.Row="3" Margin="150,0" VerticalAlignment="Top">
                    <DataGrid Name="dgvCurrency" AutoGenerateColumns="False" Height="180" Margin="10" Width="480" Background="Transparent" CanUserAddRows="False" SelectedCellsChanged="dgvCurrency_SelectedCellsChanged" SelectionUnit="Cell" VerticalScrollBarVisibility="Auto">
                        <DataGrid.Columns>
                            <DataGridTextColumn x:Name="Id" Header="Id" Width="100" CanUserResize="False" Visibility="Hidden" Binding="{Binding Path=Id}"/>
                            <DataGridTemplateColumn Header="" Width="70" IsReadOnly="True" DisplayIndex="0">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <Image Source="Images\edit-button.png" ToolTip="Edit" Width="20" Height="20"  x:Name="Revise"/>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>

                            <DataGridTemplateColumn Header="" Width="70" IsReadOnly="True" DisplayIndex="1">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <Image Source="Images\delete-button.png" ToolTip="Delete" Width="20" Height="20"  x:Name="Delete"/>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>

                            <DataGridTextColumn x:Name="Amount" Header="Amount" Width="100" CanUserResize="False" CanUserReorder="False" Binding="{Binding Path=Amount}" IsReadOnly="True"/>
                            <DataGridTextColumn x:Name="CurrencyName" Header="Currency Name" Width="*" MinWidth="20" CanUserResize="False" CanUserReorder="False" Binding="{Binding Path=CurrencyName}" IsReadOnly="True"/>
                        </DataGrid.Columns>
                    </DataGrid>
                </StackPanel>
                <StackPanel Grid.Row="4" Height="150" Width="800" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
                    <Image Height="150" Width="150" Source="Images\Logo.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="325 0"/>
                </StackPanel>
            </Grid>
        </TabItem>
    </TabControl>
</Window>

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:-

CREATE TABLE [dbo].[Currency_Master] (
    [Id]           INT           IDENTITY (1, 1) NOT NULL,
    [Amount]       FLOAT (53)    NULL,
    [CurrencyName] NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

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.

<connectionStrings>
    <add name ="ConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Hp\source\repos\CurrencyConverter_Database\Database\CurrencyConverter.mdf;Integrated Security=True"/>
</connectionStrings>

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CurrencyConverter_Database
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

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.

using System.Windows;

namespace CurrencyConverter_Database
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
  • 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:
using System.Windows;
using System.Data.SqlClient;

namespace CurrencyConverter_Database
{
    public partial class MainWindow: Window
    {
       //Create an object for SqlConnection        
       SqlConnection con = new SqlConnection();    
       
      //Create an object for SqlCommand
      SqlCommand cmd = new SqlCommand();

      //Create object for SqlDataAdapter
      SqlDataAdapter da = new SqlDataAdapter();
      
      public MainWindow()
        {
            InitializeComponent();
        }
    }
}

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.
public void mycon()
{
    //Database connection string
    String Conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    con = new SqlConnection(Conn);
    con.Open(); //Connection Open
}

Bind Currency From and To Combobox

Create a private method as BindCurrency().

//Create a method for binding the currency name and currency value using From currency and To currency Combobox
private void 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.
mycon();

//Create an object for DataTable
DataTable dt = new DataTable();

//Write query for get data from Currency_Master table
cmd = new SqlCommand("select Id, CurrencyName from Currency_Master", con);

//CommandType define which type of command we use for write a query
cmd.CommandType = CommandType.Text;

//It accepts a parameter that contains the command text of the object's selectCommand property.
da = new SqlDataAdapter(cmd);

da.Fill(dt);
  • 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.
//Create an object for DataRow
DataRow newRow = dt.NewRow();

//Assign a value to Id column
newRow["Id"] = 0;

//Assign value to CurrencyName column
newRow["CurrencyName"] = "--SELECT--";

//Insert a new row in dt with the data at a 0 position
dt.Rows.InsertAt(newRow, 0);
  • 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.
//The dt is not null and rows count greater than 0
if (dt != null && dt.Rows.Count > 0)
{
    //Assign the datatable data to from currency combobox using ItemSource property.
    cmbFromCurrency.ItemsSource = dt.DefaultView;

    //Assign the datatable data to to currency combobox using ItemSource property.
    cmbToCurrency.ItemsSource = dt.DefaultView;
}
con.Close();

//To display the underlying datasource for cmbFromCurrency
cmbFromCurrency.DisplayMemberPath = "CurrencyName";

//To use as the actual value for the items
cmbFromCurrency.SelectedValuePath = "Id";

//Show default item in combobox
cmbFromCurrency.SelectedValue = 0;

cmbToCurrency.DisplayMemberPath = "CurrencyName";
cmbToCurrency.SelectedValuePath = "Id";
cmbToCurrency.SelectedValue = 0;

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.
//This method is used to clear all the controls input which user entered
private void ClearControls()
{
    try
    {
        //Clear amount textbox text
        txtCurrency.Text = string.Empty;

        //From currency combobox items count greater than 0
        if (cmbFromCurrency.Items.Count > 0)
        {
            //Set from currency combobox selected item hint
            cmbFromCurrency.SelectedIndex = 0;
        }

        //To currency combobox items count greater than 0
        if (cmbToCurrency.Items.Count > 0)
        {
            //Set to currency combobox selected item hint
            cmbToCurrency.SelectedIndex = 0;
        }

        //Clear a label text
        lblCurrency.Content = "";

        //Set focus on amount textbox
        txtCurrency.Focus();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}
  • 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.
//Allow only integer in TextBox
{
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)

    //Regular Expression to add regex. Add library using System.Text.RegularExpressions;
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}
  • Create the new method – ClearMaster().
  • This method is used to clear all control data which the user entered.
//Method is used to clear all the input which the user has entered in currency master tab
private void ClearMaster()
{
    try
    {
        txtAmount.Text = string.Empty;
        txtCurrencyName.Text = string.Empty;
        btnSave.Content = "Save";
        GetData();
        CurrencyId = 0;
        BindCurrency();
        txtAmount.Focus();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}
  • Assign the save button click event.
private void btnSave_Click(object sender, RoutedEventArgs e)
{

}
  • 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.
try
{

}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
  • 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.”
//Check the validation 
if (txtAmount.Text == null || txtAmount.Text.Trim() == "")
{
    MessageBox.Show("Please enter amount", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
    txtAmount.Focus();
    return;
} else if (txtCurrencyName.Text == null || txtCurrencyName.Text.Trim() == "")
{
    MessageBox.Show("Please enter currency name", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
    txtCurrencyName.Focus();
    return;
}
  • 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.
if (MessageBox.Show("Are you sure you want to Save ?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
    mycon();
    DataTable dt = new DataTable();
    cmd = new SqlCommand("INSERT INTO Currency_Master(Amount, CurrencyName) VALUES(@Amount, @CurrencyName)", con);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@Amount", txtAmount.Text);
    cmd.Parameters.AddWithValue("@CurrencyName", txtCurrencyName.Text);
    cmd.ExecuteNonQuery();
    con.Close();

    MessageBox.Show("Data saved successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
}

Bind Datagrid:

//Bind Data in DataGrid View.
public void GetData()   
{
    //The method is used for connect with database and open database connection    
    mycon(); 

    //Create Datatable object
    DataTable dt = new DataTable();     

    //Write Sql Query for Get data from database table. Query written in double quotes and after comma provide connection    
    cmd = new SqlCommand("SELECT * FROM Currency_Master", con);

    //CommandType define Which type of command execute like Text, StoredProcedure, TableDirect.    
    cmd.CommandType = CommandType.Text;   
    
    //It is accept a parameter that contains the command text of the object's SelectCommand property.
    da = new SqlDataAdapter(cmd);    

    //The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The Fill operation then adds the rows to destination DataTable objects in the DataSet    
    da.Fill(dt);      
    
    //dt is not null and rows count greater than 0
    if (dt != null && dt.Rows.Count > 0)
    { 
    //Assign DataTable data to dgvCurrency using ItemSource property.   
    dgvCurrency.ItemsSource = dt.DefaultView;
    } else {
        dgvCurrency.ItemsSource = null;
     }   
   //Database connection Close
   con.Close();
}

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.
//DataGrid selected cell changed event
private void dgvCurrency_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) 
{
    try
    {
        //Create object for DataGrid
        DataGrid grd = (DataGrid)sender;
        //Create object for DataRowView
        DataRowView row_selected = grd.CurrentItem as DataRowView;

        //row_selected is not null
        if (row_selected != null)   
        {

           //dgvCurrency items count greater than zero
            if (dgvCurrency.Items.Count > 0)
            {
                if (grd.SelectedCells.Count > 0)
                {

                   //Get selected row Id column value and Set in CurrencyId variable
                    CurrencyId = Int32.Parse(row_selected["Id"].ToString());

                   //DisplayIndex is equal to zero than it is Edit cell
                    if (grd.SelectedCells[0].Column.DisplayIndex == 0)
                    {

                    //Get selected row Amount column value and Set in Amount textbox
                     txtAmount.Text = row_selected["Amount"].ToString();

                    //Get selected row CurrencyName column value and Set in CurrencyName textbox
                     txtCurrencyName.Text = row_selected["CurrencyName"].ToString();     
                    
                    //Change save button text Save to Update
                     btnSave.Content = "Update";
                    }

                //DisplayIndex is equal to one than it is Delete cell                    
                if (grd.SelectedCells[0].Column.DisplayIndex == 1)
                    {
                        //Show confirmation dialogue box
                        if (MessageBox.Show("Are you sure you want to delete ?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            mycon();
                            DataTable dt = new DataTable();
                            
                            //Execute delete query for delete record from table using Id
                            cmd = new SqlCommand("DELETE FROM Currency_Master WHERE Id = @Id", con);
                            cmd.CommandType = CommandType.Text;

                           //CurrencyId set in @Id parameter and send it in delete statement
                            cmd.Parameters.AddWithValue("@Id", CurrencyId);
                            cmd.ExecuteNonQuery();
                            con.Close();

                            MessageBox.Show("Data deleted successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            ClearMaster();
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}

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.
if (CurrencyId != 0 && CurrencyId > 0)
{
    if (MessageBox.Show("Are you sure you want to Update ?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
    {
        mycon();
        DataTable dt = new DataTable();
        cmd = new SqlCommand("UPDATE Currency_Master SET Amount = @Amount, CurrencyName = @CurrencyName WHERE Id = @Id", con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@Id", CurrencyId);
        cmd.Parameters.AddWithValue("@Amount", txtAmount.Text);
        cmd.Parameters.AddWithValue("@CurrencyName", txtCurrencyName.Text);
        cmd.ExecuteNonQuery();
        con.Close();

        MessageBox.Show("Data Updated successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
    }
}

Create a cancel button click event:

//Cancel button click event
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
    try
    {
        ClearMaster();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}

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.
//From currency combobox selection changed event for get amount of currency on selection change of currency name
private void cmbFromCurrency_SelectionChanged(object sender, SelectionChangedEventArgs e)  
{
    try
    {
        //Check condition cmbFromCurrency.SelectedValue not is equal to null and not equal to zero
		if (cmbFromCurrency.SelectedValue != null && int.Parse(cmbFromCurrency.SelectedValue.ToString()) != 0 && cmbFromCurrency.SelectedIndex != 0)   
        {
            //cmbFromCurrency.SelectedValue set in CurrencyFromId variable
			int CurrencyFromId = int.Parse(cmbFromCurrency.SelectedValue.ToString());

            mycon();
            DataTable dt = new DataTable();
            
			//Select query for get Amount from database using id
			cmd = new SqlCommand("SELECT Amount FROM Currency_Master WHERE Id = @CurrencyFromId", con);
            cmd.CommandType = CommandType.Text;
            
			//CurrencyFromId set in @CurrencyFromId parameter and send parameter in our query
			if (CurrencyFromId != null && CurrencyFromId != 0) {
                cmd.Parameters.AddWithValue("@CurrencyFromId", CurrencyFromId);
				}
            da = new SqlDataAdapter(cmd);
            
			//Set the data that the query returns in the data table
			da.Fill(dt);
            if (dt != null && dt.Rows.Count > 0) {
                //Get amount column value from datatable and set amount value in FromAmount variable which is declared globally
				FromAmount = double.Parse(dt.Rows[0]["Amount"].ToString());
                }         
		 con.Close();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}

To currency Combobox selection changed event:

//To currency combobox selection changed event for get amount of currency on selection change of currency name
private void cmbToCurrency_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    try
    {
        //Check condition cmbToCurrency SelectedValue not is equal to null and not equal to zero
		if (cmbToCurrency.SelectedValue != null && int.Parse(cmbToCurrency.SelectedValue.ToString()) != 0 && cmbToCurrency.SelectedIndex != 0)
        {
             //cmbToCurrency SelectedValue set in CurrencyToId variable
			int CurrencyToId = int.Parse(cmbToCurrency.SelectedValue.ToString());

            mycon();
            DataTable dt = new DataTable();
            
			//Select query for get Amount from database using id
			cmd = new SqlCommand("SELECT Amount FROM Currency_Master WHERE Id = @CurrencyToId", con);
            cmd.CommandType = CommandType.Text;
            
			//CurrencyToId set in @CurrencyToId parameter and send parameter in our query
			if (CurrencyToId != null && CurrencyToId != 0){
                cmd.Parameters.AddWithValue("@CurrencyToId", CurrencyToId);
				}
            
			da = new SqlDataAdapter(cmd);
            //Set the data that the query returns in the data table
			da.Fill(dt);
            if (dt != null && dt.Rows.Count > 0){
				//Get amount column value from datatable and set amount value in ToAmount variable which is declared globally            
					ToAmount = double.Parse(dt.Rows[0]["Amount"].ToString());
			}
            con.Close();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}

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.
//cmbFromCurrency preview key down event
private void cmbFromCurrency_PreviewKeyDown(object sender, KeyEventArgs e)
{
    //If the user press Tab or Enter key then cmbFromCurrency_SelectionChanged event fire
	if (e.Key == Key.Tab || e.SystemKey == Key.Enter)
    {
        cmbFromCurrency_SelectionChanged(sender, null);
    }
}

//cmbToCurrency preview key down event
private void cmbToCurrency_PreviewKeyDown(object sender, KeyEventArgs e)
{
    //If the user press Tab or Enter key then cmbToCurrency_SelectionChanged event fire
	if (e.Key == Key.Tab || e.SystemKey == Key.Enter)
    {
        cmbToCurrency_SelectionChanged(sender, null);
    }
}

Calculation of Currency Converter:

//Convert button click event
private void Convert_Click(object sender, RoutedEventArgs e)
{

}

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.”
//Declare ConvertedValue with double data type for store currency converted value
double ConvertedValue;

//Check amount textbox is Null or Blank
if (txtCurrency.Text == null || txtCurrency.Text.Trim() == "")
{
    //If amount Textbox is Null or Blank show the below message box
	MessageBox.Show("Please Enter Currency", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
    //After click on OK button set focus on amount textbox
	txtCurrency.Focus();
    return;
}
//Else if currency From is not selected or select default text --SELECT--
else if (cmbFromCurrency.SelectedValue == null || cmbFromCurrency.SelectedIndex == 0)
{
    //Show the message
	MessageBox.Show("Please Select Currency From", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
    
	//Set focus to From Combobox
	cmbFromCurrency.Focus();
    return;
}
// Else if currency To is not selected or select default text --SELECT--
else if (cmbToCurrency.SelectedValue == null || cmbToCurrency.SelectedIndex == 0)
{
    //Show the message
	MessageBox.Show("Please Select Currency To", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
    //Set focus to To Combobox
	cmbToCurrency.Focus();
    return;
}
  • 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.
//If From and To Combobox selects same value
if(cmbFromCurrency.Text == cmbToCurrency.Text)
{
    //Amount textbox value set in ConvertedValue. double.parse is used for change datatype from string to double.
	//Textbox text have string and ConvertedValue as double datatype
	ConvertedValue = double.Parse(txtCurrency.Text);  
	
    //Show the label converted currency and converted currency name.
	//Tostring("N3") is used to place 000 after the dot(.)
	lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
} 
else
{
    //Calculation for currency converter is From currency value multiplied(*) with the amount textbox value and then the total is divided(/) with To currency value.
	ConvertedValue = (double.Parse(cmbFromCurrency.SelectedValue.ToString()) * double.Parse(txtCurrency.Text)) / double.Parse(cmbToCurrency.SelectedValue.ToString());
    
	//Show the label converted currency and converted currency name.
	lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
}
  • Create a clear button click event.
  • Call ClearControls() method for clear all controls input which user entered.
//Clear Button Click Event
private void Clear_Click(object sender, RoutedEventArgs e)
{
    //ClearControls Method for Clear All Control Value
    ClearControls();
}

Final code of MainWindow.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System;

//This namespace is used for DataTable
using System.Data;

//This namespace is used for Regular Expression
using System.Text.RegularExpressions;

//This namespace is used for SQL Classes
using System.Data.SqlClient;

//This namespace is used for ConfigurationManager and ConfigurationManager is used to fetch connection string from App.config file.
using System.Configuration;

//The class names declared in one namespace should not conflict with the same class names declared in another.
namespace CurrencyConverter_Database
{
    public partial class MainWindow : Window
    {

        //Create object for SqlConnection
		SqlConnection con = new SqlConnection();    
		
        //Create an object for SqlCommand
		SqlCommand cmd = new SqlCommand();
		
        //Create object for SqlDataAdapter
		SqlDataAdapter da = new SqlDataAdapter();

        //Declare CurrencyId with int data type and assign value as 0.
		private int CurrencyId = 0;
        
		//Declare FromAmount with double data type and assign value 0.
		private double FromAmount = 0;
		
		//Declare ToAmount with double data type and assign value 0.
        private double ToAmount = 0;

        public MainWindow()
        {
            //We drag controls to the form in Visual Studio. Behind the scenes, Visual Studio adds code to the InitializeComponent method
			InitializeComponent();  
            
			//ClearControls method to clear all controls value
			ClearControls();
            
			//BindCurrency is used for bind currrency name with value in Combobox
			BindCurrency();
            
			//GetData method is used to bind DataGrid
			GetData();
        }

        public void mycon()
        {
            //Database connection string
			String Conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            con = new SqlConnection(Conn);
            
			//Open the connection
			con.Open();
        }

        //Bind the currency name to From currency and To currency Combobox.
		private void BindCurrency()
        {
            mycon();
            
			//Create Object for DataTable
			DataTable dt = new DataTable();
            
			//Write SQL Query for Get Data from Database Table.
			cmd = new SqlCommand("select Id, CurrencyName from Currency_Master", con);
            
			//CommandType Define Which type of Command we Use for Write a Query
			cmd.CommandType = CommandType.Text;
            
			//It accepts a parameter that contains the command text of the object's SelectCommand property.
			da = new SqlDataAdapter(cmd);
            da.Fill(dt);
			
            //Create a DataRow object
			DataRow newRow = dt.NewRow();
            
			//Assign a value to Id column
			newRow["Id"] = 0;
            
			//Assign value to CurrencyName column
			newRow["CurrencyName"] = "--SELECT--";
            
			//Insert a new row in dt with a data at 0 position
			dt.Rows.InsertAt(newRow, 0); 

            //dt is not null and rows count greater than 0
			if (dt != null && dt.Rows.Count > 0)
            {
                //Assign data table data to From currency Combobox using item source property.
				cmbFromCurrency.ItemsSource = dt.DefaultView;
				
                //Assign data table data to To currency Combobox using item source property.
				cmbToCurrency.ItemsSource = dt.DefaultView;
            }
            con.Close();

            //To display the underlying datasource for cmbFromCurrency
			cmbFromCurrency.DisplayMemberPath = "CurrencyName";
			
			
            //To use as the actual value for the items
			cmbFromCurrency.SelectedValuePath = "Id";
			
			//Show default item in Combobox
            cmbFromCurrency.SelectedValue = 0;       

            cmbToCurrency.DisplayMemberPath = "CurrencyName";
            cmbToCurrency.SelectedValuePath = "Id";
            cmbToCurrency.SelectedValue = 0;

        }

        #region Extra Events
        //Method is used to clear all the input which user entered
		private void ClearControls()
        {
            try
            {
                txtCurrency.Text = string.Empty;
                if (cmbFromCurrency.Items.Count > 0)
                    cmbFromCurrency.SelectedIndex = 0;
                if (cmbToCurrency.Items.Count > 0)
                    cmbToCurrency.SelectedIndex = 0;
                lblCurrency.Content = "";
                txtCurrency.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //Allow only integer in the Textbox
		private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            //Regular expression to add Regex. Add library using System.Text.RegularExpressions;
			Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }
        #endregion

        #region Currency Converter Tab Button Click Event
        
		// Assign the click event to convert button
		private void Convert_Click(object sender, RoutedEventArgs e)
        {
            try
            {
			    //Declare ConvertedValue variable with double data type to store converted currency value
                double ConvertedValue;  
                
				//Check amount textbox is Null or Blank
				if (txtCurrency.Text == null || txtCurrency.Text.Trim() == "") 
                {
                    //If amount Textbox is Null or Blank then show dialog box
					MessageBox.Show("Please enter currency", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    
					//Set focus to amount textbox
					txtCurrency.Focus();
                    return;
                }
                //If From currency selected value is null or default text as --SELECT--
				else if (cmbFromCurrency.SelectedValue == null || cmbFromCurrency.SelectedIndex == 0)
                {
                    //Open Dialog box
					MessageBox.Show("Please select from currency", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    cmbFromCurrency.Focus();
                    return;
                }
                else if (cmbToCurrency.SelectedValue == null || cmbToCurrency.SelectedIndex == 0)
                {
                    MessageBox.Show("Please select to currency", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    cmbToCurrency.Focus();
                    return;
                }

                if (cmbFromCurrency.SelectedValue == cmbToCurrency.SelectedValue)   //Check if From and To Combobox Selected Same Value
                {
                    //Amount textbox value is set in ConvertedValue. The double.parse is used to change Datatype from String To Double. 
					//Textbox text has string, and ConvertedValue is double.
					ConvertedValue = double.Parse(txtCurrency.Text);    
                    
					//Show the label converted currency name and converted currency amount. The ToString("N3") is used for Placing 000 after the dot(.)
					lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
                }
                else
                {
                    if (FromAmount != null && FromAmount != 0 && ToAmount != null && ToAmount != 0)
                    {
                        //Calculation for currency converter is From currency value Multiplied(*) with amount textbox value and then that total is divided(/) with To currency value.
						ConvertedValue = FromAmount * double.Parse(txtCurrency.Text) / ToAmount;
                        
						
						//Show the label converted currency name and converted currency amount.
						lblCurrency.Content = cmbToCurrency.Text + " " + ConvertedValue.ToString("N3");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //Assign the clear button click event
		private void Clear_Click(object sender, RoutedEventArgs e)
        {
            //ClearControls method used to clear all the control values which user entered
			ClearControls();
        }
        #endregion

        #region Currency Master Button Click Event
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtAmount.Text == null || txtAmount.Text.Trim() == "")
                {
                    MessageBox.Show("Please enter amount", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    txtAmount.Focus();
                    return;
                }
                else if (txtCurrencyName.Text == null || txtCurrencyName.Text.Trim() == "")
                {
                    MessageBox.Show("Please enter currency name", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    txtCurrencyName.Focus();
                    return;
                }
                else
                {   //Edit time and set that record Id in CurrencyId variable.
                    //Code to Update. If CurrencyId greater than zero than it is go for update.
					if (CurrencyId > 0)
                    {
                        //Show the confirmation message
						if (MessageBox.Show("Are you sure you want to update ?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            mycon();
                            DataTable dt = new DataTable();
                            
							//Update Query Record update using Id
							cmd = new SqlCommand("UPDATE Currency_Master SET Amount = @Amount, CurrencyName = @CurrencyName WHERE Id = @Id", con);
                            cmd.CommandType = CommandType.Text;
                            cmd.Parameters.AddWithValue("@Id", CurrencyId);
                            cmd.Parameters.AddWithValue("@Amount", txtAmount.Text);
                            cmd.Parameters.AddWithValue("@CurrencyName", txtCurrencyName.Text);
                            cmd.ExecuteNonQuery();
                            con.Close();

                            MessageBox.Show("Data updated successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
					// Code to Save
                    else
                    {
                        if (MessageBox.Show("Are you sure you want to save ?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            mycon();
                            //Insert query to Save data in the table
							cmd = new SqlCommand("INSERT INTO Currency_Master(Amount, CurrencyName) VALUES(@Amount, @CurrencyName)", con);
                            cmd.CommandType = CommandType.Text;
                            cmd.Parameters.AddWithValue("@Amount", txtAmount.Text);
                            cmd.Parameters.AddWithValue("@CurrencyName", txtCurrencyName.Text);
                            cmd.ExecuteNonQuery();
                            con.Close();

                            MessageBox.Show("Data saved successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                    ClearMaster();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

         //Assign the cancel button click event
		private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ClearMaster();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        //Bind data to the DataGrid view.
		public void GetData()
        {
            
			//Method is used for connect with database and open database connection
			mycon();    
            
			//Create Datatable object
			DataTable dt = new DataTable();     
            
			//Write SQL query to get the data from database table. Query written in double quotes and after comma provide connection.
			cmd = new SqlCommand("SELECT * FROM Currency_Master", con);
            
			//CommandType define which type of command will execute like Text, StoredProcedure, TableDirect.
			cmd.CommandType = CommandType.Text;
            
			//It is accept a parameter that contains the command text of the object's SelectCommand property.
			da = new SqlDataAdapter(cmd);
            
			//The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. 
			//The fill operation then adds the rows to destination DataTable objects in the DataSet
			da.Fill(dt);
            
			//dt is not null and rows count greater than 0
			if (dt != null && dt.Rows.Count > 0)
                //Assign DataTable data to dgvCurrency using item source property.
				dgvCurrency.ItemsSource = dt.DefaultView;
            else
                dgvCurrency.ItemsSource = null;
            
			//Database connection close
			con.Close();
        }

        //Method is used to clear all the input which user entered in currency master tab
		private void ClearMaster()
        {
            try
            {
                txtAmount.Text = string.Empty;
                txtCurrencyName.Text = string.Empty;
                btnSave.Content = "Save";
                GetData();
                CurrencyId = 0;
                BindCurrency();
                txtAmount.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //DataGrid selected cell changed event
		private void dgvCurrency_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            try
            {
                //Create object for DataGrid
				DataGrid grd = (DataGrid)sender;
				
                //Create an object for DataRowView
				DataRowView row_selected = grd.CurrentItem as DataRowView;

                //If row_selected is not null
				if (row_selected != null)
                {
                    //dgvCurrency items count greater than zero
					if (dgvCurrency.Items.Count > 0)
                    {
                        if (grd.SelectedCells.Count > 0)
                        {
                            //Get selected row id column value and set it to the CurrencyId variable
							CurrencyId = Int32.Parse(row_selected["Id"].ToString());

                            //DisplayIndex is equal to zero in the Edited cell
							if (grd.SelectedCells[0].Column.DisplayIndex == 0)
                            {
                                //Get selected row amount column value and set to amount textbox
								txtAmount.Text = row_selected["Amount"].ToString();
                                
								//Get selected row CurrencyName column value and set it to CurrencyName textbox
								txtCurrencyName.Text = row_selected["CurrencyName"].ToString();
                                btnSave.Content = "Update";     //Change save button text Save to Update
                            }
                            
							//DisplayIndex is equal to one in the deleted cell
							if (grd.SelectedCells[0].Column.DisplayIndex == 1)
                            {
                                //Show confirmation dialog box
								if (MessageBox.Show("Are you sure you want to delete ?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                                {
                                    mycon();
                                    DataTable dt = new DataTable();
                                    
									//Execute delete query to delete record from table using Id
									cmd = new SqlCommand("DELETE FROM Currency_Master WHERE Id = @Id", con);
                                    cmd.CommandType = CommandType.Text;
                                    
									//CurrencyId set in @Id parameter and send it in delete statement
									cmd.Parameters.AddWithValue("@Id", CurrencyId);
                                    cmd.ExecuteNonQuery();
                                    con.Close();

                                    MessageBox.Show("Data deleted successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                                    ClearMaster();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #region Selection Changed Events
        
		//From currency Combobox selection changed event to get the amount of currency on selection change of currency name
		private void cmbFromCurrency_SelectionChanged(object sender, SelectionChangedEventArgs e)  
        {
            try
            {
                //If cmbFromCurrency selected value is not equal to null and not equal to zero
				if (cmbFromCurrency.SelectedValue != null && int.Parse(cmbFromCurrency.SelectedValue.ToString()) != 0 && cmbFromCurrency.SelectedIndex != 0)
                {
                    //cmbFromCurrency selectedvalue set in CurrencyFromId variable
					int CurrencyFromId = int.Parse(cmbFromCurrency.SelectedValue.ToString());

                    mycon();
                    DataTable dt = new DataTable();
                    
					//Select query to get amount from database using id
					cmd = new SqlCommand("SELECT Amount FROM Currency_Master WHERE Id = @CurrencyFromId", con);
                    cmd.CommandType = CommandType.Text;
					
                    if (CurrencyFromId != null && CurrencyFromId != 0)
                        //CurrencyFromId set in @CurrencyFromId parameter and send parameter in our query
						cmd.Parameters.AddWithValue("@CurrencyFromId", CurrencyFromId);
                    
					da = new SqlDataAdapter(cmd);
					
                    //Set the data that the query returns in the data table
					da.Fill(dt);
                    
					if (dt != null && dt.Rows.Count > 0)
					//Get amount column value from datatable and set amount value in From amount variable which is declared globally
					FromAmount = double.Parse(dt.Rows[0]["Amount"].ToString());     
                    
					con.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        
		//To currency Combobox selection changed event to get the amount of currency on selection change of currency name
		private void cmbToCurrency_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                 //If cmbToCurrency selectedvalue is not equal to null and not equal to zero
				if (cmbToCurrency.SelectedValue != null && int.Parse(cmbToCurrency.SelectedValue.ToString()) != 0 && cmbToCurrency.SelectedIndex != 0)
                {
                    //cmbToCurrency selectedvalue is set to CurrencyToId variable
					int CurrencyToId = int.Parse(cmbToCurrency.SelectedValue.ToString());

                    mycon();
					
                    DataTable dt = new DataTable();
                    //Select query for get Amount from database using id
					cmd = new SqlCommand("SELECT Amount FROM Currency_Master WHERE Id = @CurrencyToId", con);
                    cmd.CommandType = CommandType.Text;
					
                    if (CurrencyToId != null && CurrencyToId != 0)
                        //CurrencyToId set in @CurrencyToId parameter and send parameter in our query
						cmd.Parameters.AddWithValue("@CurrencyToId", CurrencyToId);
                    
					da = new SqlDataAdapter(cmd);
                    
					//Set the data that the query returns in the data table
					da.Fill(dt);
                    
					if (dt != null && dt.Rows.Count > 0)
                        //Get amount column value from datatable and set amount value in ToAmount variable which is declared globally
						ToAmount = double.Parse(dt.Rows[0]["Amount"].ToString());
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        #region Preview Key Down Events
        //cmbFromCurrency preview key down event
		private void cmbFromCurrency_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //If the user press Tab or Enter key then cmbFromCurrency_SelectionChanged event is executed
			if (e.Key == Key.Tab || e.SystemKey == Key.Enter)
            {
                cmbFromCurrency_SelectionChanged(sender, null);
            }
        }

        //cmbToCurrency preview key down event
		private void cmbToCurrency_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //If the user press Tab or Enter key then cmbToCurrency_SelectionChanged event is executed
			if (e.Key == Key.Tab || e.SystemKey == Key.Enter)
            {
                cmbToCurrency_SelectionChanged(sender, null);
            }
        }
        #endregion
    }
}

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