Thursday, 1 March 2012

Simple ADO .Net Project


A Mortgage company has asked you to develop a registration system for its client using .NET Framework. The system should be able to:
- Add new client to the database.
- Update client data
- Delete client data
- Search client data by client’s name
- Search client data by client’s address
- query on the total number of mortgage received by the client,

- The data for each client containing ClientID, name, address, phone number and photo stores in the ClientInfo Table.

- Each client is able to take several mortgages from the company. The mortgage data for each client stores in the Mortgage Table. The table contains ClientID, mortgage amount , interest rate, and the interest term(months).
- The relationship between ClientInfo and Mortgage table is one-to-many (1: n).

 
AddClient.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace VDesai_Assign2
{
    public partial class AddClient : Form
    {
        public AddClient()
        {
            InitializeComponent();
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=L119-N-SMS006;Initial Catalog=MortgageSystem;Integrated Security=True ; MultipleActiveResultSets = true");

            SqlCommand insertcmd = new SqlCommand("Insert into Mortgage (ClientID, MortgageAmount,InterestRate,InterestTerm)Values(@ClientID,@MortgageAmount,@InterestRate,@InterestTerm);", con);

            con.Open();
            //da.SelectCommand = new SqlCommand(s, con);
            insertcmd.Parameters.Add("@ClientID", SqlDbType.Int, 2).Value = IDMortTxt.Text;
            insertcmd.Parameters.Add("@MortgageAmount", SqlDbType.Decimal).Value = AmountTxt.Text;
            insertcmd.Parameters.Add("@InterestRate", SqlDbType.Decimal).Value = RateTxt.Text ;
            insertcmd.Parameters.Add("@InterestTerm", SqlDbType.Int, 2).Value = Interesttxt.Text;
            insertcmd.ExecuteNonQuery();
            //da.InsertCommand = insertcmd;
            //da.Fill(dt);
            MessageBox.Show("Client Saved");
            con.Close();
            AmountTxt.Clear();
            RateTxt.Clear();
            Interesttxt.Clear();
            IDMortTxt.Clear();
        }
        //long m_lImageFileLength;
        //byte[] m_barrImg;
        private void UploadBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "ImageFiles(*.jpg;*jpeg;*.gif;*.bmp)|*.jpg;*jpeg;*.gif;*.bmp";
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
                PathTxt.Text = openFileDialog1.FileName;

            }
            //try
            //{
            //    openFileDialog1.ShowDialog(this);
            //    string strFn = openFileDialog1.FileName;
               
            //    this.pictureBox1.Image = Image.FromFile(strFn);
            //    FileInfo fiImage = new FileInfo(strFn);
               
            //    m_lImageFileLength = fiImage.Length;
            //    FileStream fs = new FileStream(strFn, FileMode.Open,
            //                      FileAccess.Read, FileShare.Read);
               
            //     m_barrImg = new byte[Convert.ToInt32(this.m_lImageFileLength)];
            //    int iBytesRead = fs.Read(m_barrImg, 0,
            //                     Convert.ToInt32(this.m_lImageFileLength));
            //    fs.Close();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }

        private void AddClient_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'mortgageSystemDataSet.Mortgage' table. You can move, or remove it, as needed.
            //this.mortgageTableAdapter.Fill(this.mortgageSystemDataSet.Mortgage);
            PathTxt.Enabled = false;
        }

       
        private void SaveClient_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=L119-N-SMS006;Initial Catalog=MortgageSystem;Integrated Security=True ; MultipleActiveResultSets = true");
            SqlCommand cmd = new SqlCommand("Insert into ClientInfo (ClientID,Name,Street,City,Province,PostalCode,Phone,Picture)Values(@ClientID,@Name,@Street,@City,@Province,@PostalCode,@Phone,@Picture);", con);
            string sPath = PathTxt.Text;
            FileStream fs = new FileStream(sPath, FileMode.Open, FileAccess.Read);
            byte[] imageData = new byte[fs.Length];
            fs.Read(imageData, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            SqlParameter prm = new SqlParameter("@Picture",SqlDbType.VarBinary ,imageData.Length,ParameterDirection.Input ,false,0,0,null,DataRowVersion.Current,imageData );
           
            con.Open();
            cmd.Parameters.Add("@ClientID", SqlDbType.Int, 2).Value = IDTxt.Text;
            cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = NameTxt.Text;
            cmd.Parameters.Add("@Street", SqlDbType.VarChar, 50).Value = StreetTxt.Text;
            cmd.Parameters.Add("@City", SqlDbType.VarChar, 50).Value = CityTxt.Text;
            cmd.Parameters.Add("@Province", SqlDbType.VarChar, 50).Value = ProvinceTxt.Text;
            cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 50).Value = PostalTxt.Text;
            cmd.Parameters.Add("@Phone", SqlDbType.BigInt).Value = PhoneTxt.Text;
           // cmd.Parameters.Add("@Picture",SqlDbType.Image ).Value = m_barrImg ;
            cmd.Parameters.Add(prm);
            cmd.ExecuteNonQuery();
            IDTxt.Clear();
            NameTxt.Clear();
            StreetTxt.Clear();
            CityTxt.Clear();
            ProvinceTxt.Clear();
            PostalTxt.Clear();
            PhoneTxt.Clear();
            PathTxt.Clear();
            pictureBox1.Image = Image.FromFile("C:\\Pictures\\index.jpg");
           
        }

        private void ResetBtn_Click(object sender, EventArgs e)
        {
           
           
           
        }

        private void NameTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (!(e.KeyValue > 58 || e.KeyValue < 49))
            {
                MessageBox.Show("Please Enter text only!");
                NameTxt.Text = "";
                NameTxt.Focus();
            }
        }

        private void CityTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (!(e.KeyValue > 58 || e.KeyValue < 49))
            {
                MessageBox.Show("Please Enter text only!");
                CityTxt.Text = "";
                CityTxt.Focus();
            }
        }

        private void RateTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar)
            && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if (e.KeyChar == '.'
                && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }       

        private void AmountTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar)
            && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if (e.KeyChar == '.'
                && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
           }
        }

        private void Interesttxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar))   
            {
                e.Handled = true;
           }          
        }

        private void MortgageTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }                       
        }

        private void ResetClientBtn_Click(object sender, EventArgs e)
        {
           
           
        }            
    }
}


View-Edit-Search-Delete.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace VDesai_Assign2
{
    public partial class RegisForm : Form
    {
        public RegisForm()
        {
            InitializeComponent();
        }
       
        private void EditBtn_Click(object sender, EventArgs e)
        {
            NameTxt.Enabled = true;
            StreetTxt.Enabled = true;
            CityTxt.Enabled = true;
            ProvinceTxt.Enabled = true;
            PostalTxt.Enabled = true;
            PhoneTxt.Enabled = true;
            UploadBtn.Enabled = true;
            dataGridView1.Enabled = true;                                      
        }

        private void RegisForm_Load(object sender, EventArgs e)
        {
            SqlDataReader rdr = null;
            IDTxt.Enabled = false;
            NameTxt.Enabled = false;
            StreetTxt.Enabled = false;
            CityTxt.Enabled = false;
            ProvinceTxt.Enabled = false;
            PostalTxt.Enabled = false;
            PhoneTxt.Enabled = false;
            MortgageTxt.Enabled = false;
            UploadBtn.Enabled = false;
            dataGridView1.Enabled = false;
            SqlConnection con = new SqlConnection("Data Source=L119-N-SMS006;Initial Catalog=MortgageSystem;Integrated Security=True");

            try
            {
                con.Open();
                string sql = @"Select ClientID from ClientInfo;";              
                SqlCommand cmd = new SqlCommand(sql, con);
                rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    IDList.Items.Add(rdr["ClientID"].ToString());                   
                }


            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (rdr != null)
                    rdr.Close();
                if (con.State == ConnectionState.Open)
                    con.Close();
            }
        }      
        private void pictureFormat(object sender, ConvertEventArgs e)
        {
            byte[] img = (byte[])e.Value;
            MemoryStream ms = new MemoryStream(img);
            Bitmap bmp = new Bitmap(ms);
            ms.Close();
            e.Value = bmp;
        }

        private void IDList_SelectedIndexChanged_1(object sender, EventArgs e)
        {                       
            SqlDataReader dr = null;
            SqlConnection con = new SqlConnection("Data Source=L119-N-SMS006;Initial Catalog=MortgageSystem;Integrated Security=True;MultipleActiveResultSets=True");
            try
            {
                con.Open();
                int clientid = Convert.ToInt32(IDList.SelectedItem);
                string sql = @"Select ClientID, Name,Street,City,Province,PostalCode,Phone,Picture from ClientInfo where ClientID = '"+IDList.SelectedItem +"'";
                string imgsql = @"Select Picture from ClientInfo where ClientID = '" + IDList.SelectedItem + "'";
                string mortsql = @"Select MortgageAmount,Interestrate,InterestTerm from Mortgage join ClientInfo on Mortgage.ClientID = ClientInfo.ClientID where ClientInfo.ClientID = '"+IDList.SelectedItem+"'";
                string count = @"select COUNT(Mortgage.ClientID) as NoOfMortgage from Mortgage join ClientInfo on Mortgage.ClientID = ClientInfo.ClientID where ClientInfo.ClientID = '"+IDList.SelectedItem+"' group by Mortgage.ClientID";
                SqlDataAdapter da = new SqlDataAdapter(mortsql,con);
                DataTable dt = new DataTable();
                da.Fill(dt);
                BindingSource bd = new BindingSource();
                bd.DataSource = dt;
                dataGridView1.DataSource = bd;
                SqlCommand cmd = new SqlCommand(sql, con);
                SqlCommand cmd1 = new SqlCommand(imgsql,con);
                SqlDataAdapter da1 = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da1.Fill(ds, "ClientInfo");               
                SqlCommand cmd2 = new SqlCommand(count,con);
                cmd.CommandType = CommandType.Text;
                cmd1.CommandType = CommandType.Text;
                cmd2.CommandType = CommandType.Text;
                //cmd.Parameters.Add("@ClientID", clientid);
                //byte[] img = (byte[])cmd1.ExecuteScalar();
                //string strfn = Convert.ToString(DateTime.Now.ToFileTime());
                //FileStream fs = new FileStream(strfn,
                //                  FileMode.OpenOrCreate, FileAccess.Write);
                //fs.Write(img, 0, img.Length);
                //fs.Flush();
                //fs.Close();               
               
                dr = cmd.ExecuteReader();
                int ct= Convert.ToInt32(cmd2.ExecuteScalar());
                while (dr.Read())
                {
                    IDTxt.Text = dr["ClientID"].ToString();
                    NameTxt.Text = dr["Name"].ToString();
                    StreetTxt.Text = dr["Street"].ToString();
                    CityTxt.Text = dr["City"].ToString();
                    ProvinceTxt.Text = dr["Province"].ToString();
                    PostalTxt.Text = dr["PostalCode"].ToString();
                    PhoneTxt.Text = dr["Phone"].ToString();
                    byte[] blobData = (byte[])dr["Picture"];
                    MemoryStream ms = new MemoryStream(blobData );
                    Bitmap bmp = new Bitmap(ms);
                    ms.Close();
                    pictureBox1.Image = bmp;
                   
                    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                    MortgageTxt.Text = ct.ToString();
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                    con.Close();
            }
        }

        private void NameSearchBtn_Click(object sender, EventArgs e)
        {
            SqlDataReader dr = null;
            SqlConnection con = new SqlConnection("Data Source=L119-N-SMS006;Initial Catalog=MortgageSystem;Integrated Security=True;MultipleActiveResultSets = true ");
            try
            {
                con.Open();
               // int clientid = Convert.ToInt32(IDList.SelectedItem);
                string sql = @"Select ClientID from ClientInfo where Name='"+NameSearchTxt.Text+ "'";
                SqlCommand cmd = new SqlCommand(sql, con);
                //cmd.CommandType = CommandType.Text;
                dr = cmd.ExecuteReader();
                IDList.Items.Clear();
                while (dr.Read())
                {
                    IDList.Items.Add(dr["ClientID"].ToString());                  
                }               
                //byte[] img = (byte[])cmd.ExecuteScalar();
                //string strfn = Convert.ToString(DateTime.Now.ToFileTime());
                //FileStream fs = new FileStream(strfn,
                //                  FileMode.CreateNew, FileAccess.Write);
                //fs.Write(img, 0, img.Length);
                //fs.Flush();
                //fs.Close();
                //dr = cmd.ExecuteReader();
                //while (dr.Read())
                //{
                //    IDTxt.Text = dr["ClientID"].ToString();
                //    NameTxt.Text = dr["Name"].ToString();
                //    AddressTxt.Text = dr["ClientAddress"].ToString();
                //    PhoneTxt.Text = dr["Phone"].ToString();
                //    //pictureBox1.Image = Image.FromFile(strfn);
                //}

            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if(dr!= null)
                    dr.Close();
                if (con.State == ConnectionState.Open)
                    con.Close();
            }

        }

        private void CitySearchBtn_Click(object sender, EventArgs e)
        {
             SqlDataReader dr = null;
            SqlConnection con = new SqlConnection("Data Source=L119-N-SMS006;Initial Catalog=MortgageSystem;Integrated Security=True;MultipleActiveResultSets = true ");
            try
            {
                con.Open();
                // int clientid = Convert.ToInt32(IDList.SelectedItem);
                string sql = @"Select ClientID from ClientInfo where City ='" + CitySearchTxt.Text + "'";
                SqlCommand cmd = new SqlCommand(sql, con);
                //cmd.CommandType = CommandType.Text;
                dr = cmd.ExecuteReader();
                IDList.Items.Clear();
                while (dr.Read())
                {
                    IDList.Items.Add(dr["ClientID"].ToString());
                    // IDList.Items.Add(Environment.NewLine);
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (dr != null)
                    dr.Close();
                if (con.State == ConnectionState.Open)
                    con.Close();
            }
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            string connectionstring = "Data Source=L119-N-SMS006;Initial Catalog=MortgageSystem;Integrated Security=True ; MultipleActiveResultSets = true";
            SqlConnection con = new SqlConnection(connectionstring);

            string sPath = PathTxt.Text;
            string upd = @"Update ClientInfo set Name=@Name,Street=@Street,City=@City,Province=@Province,PostalCode=@Postal,Phone=@Phone,Picture=@Picture where ClientID='" + IDList.SelectedItem + "'";
            string upd1 = @"Update ClientInfo set Name=@Name,Street=@Street,City=@City,Province=@Province,PostalCode=@Postal,Phone=@Phone where ClientID='" + IDList.SelectedItem + "'";
            if (sPath != "")
            {

                FileStream fs = new FileStream(sPath, FileMode.Open, FileAccess.Read);
                byte[] imageData = new byte[fs.Length];
                fs.Read(imageData, 0, Convert.ToInt32(fs.Length));
                fs.Close();

                //SqlDataAdapter upda = new SqlDataAdapter();
                //upda.SelectCommand = new SqlCommand(sel, con);
                //DataSet ds = new DataSet();
                //upda.Fill(ds, "ClientInfo");
                //DataTable dt = ds.Tables["ClientInfo"];

                //foreach (DataRow dr in dt.Rows)
                //{
                //    dr["Name"] = NameTxt.Text;
                //    dr["Street"] = StreetTxt.Text;
                //    dr["City"] = CityTxt.Text;
                //    dr["Province"] = ProvinceTxt.Text;
                //    dr["PostalCode"] = PostalTxt.Text;
                //    dr["Phone"] = PhoneTxt.Text;
                //    dr["Picture"] = imageData; ;
                //}
                //upda.UpdateCommand = new SqlCommand(upd, con);
                SqlCommand cmd = new SqlCommand(upd, con);
                cmd.Parameters.Add("@ClientID", SqlDbType.Int, 2).Value = IDTxt.Text.Trim();
                cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = NameTxt.Text.Trim();
                cmd.Parameters.Add("@Street", SqlDbType.VarChar, 100).Value = StreetTxt.Text.Trim();
                cmd.Parameters.Add("@City", SqlDbType.VarChar, 50).Value = CityTxt.Text.Trim();
                cmd.Parameters.Add("@Province", SqlDbType.VarChar, 50).Value = ProvinceTxt.Text.Trim();
                cmd.Parameters.Add("@Postal", SqlDbType.VarChar, 20).Value = PostalTxt.Text.Trim();
                cmd.Parameters.Add("@Phone", SqlDbType.BigInt, 12).Value = PhoneTxt.Text.Trim();
                //upda.UpdateCommand .Parameters.Add("@Picture", SqlDbType.VarBinary, 1024).Value = imageData;
                cmd.Parameters.Add("@Picture", SqlDbType.Image).Value = imageData;
                //SqlParameter uparam = upda.UpdateCommand.Parameters.Add("@ClientID", SqlDbType.Int, 2, "ClientID");
                //uparam.SourceVersion = DataRowVersion.Original;
                //upda.UpdateCommand = cmd1;
                //upda.Update(ds, "ClientInfo");
                con.Open();
                int n = cmd.ExecuteNonQuery();
                if (n > 0)
                {
                    MessageBox.Show("Record Updated...");
                }

            }
            else
            {

                SqlCommand cmd = new SqlCommand(upd1, con);
                cmd.Parameters.Add("@ClientID", SqlDbType.Int, 2).Value = IDTxt.Text.Trim();
                cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = NameTxt.Text.Trim();
                cmd.Parameters.Add("@Street", SqlDbType.VarChar, 100).Value = StreetTxt.Text.Trim();
                cmd.Parameters.Add("@City", SqlDbType.VarChar, 50).Value = CityTxt.Text.Trim();
                cmd.Parameters.Add("@Province", SqlDbType.VarChar, 50).Value = ProvinceTxt.Text.Trim();
                cmd.Parameters.Add("@Postal", SqlDbType.VarChar, 20).Value = PostalTxt.Text.Trim();
                cmd.Parameters.Add("@Phone", SqlDbType.BigInt, 12).Value = PhoneTxt.Text.Trim();
                con.Open();
                int n = cmd.ExecuteNonQuery();
                if (n > 0)
                {
                    MessageBox.Show("Record Updated...");
                }

            }
             for (int c = 0; c < dataGridView1.Rows.Count; c++)
                {
                    SqlCommand upMort = new SqlCommand("Update Mortgage set MortgageAmount = @MortgageAmount, InterestRate= @InterestRate,InterestTerm=@InterestTerm where ClientID = '" + IDList.SelectedItem + "'",con);
                    upMort.Parameters.AddWithValue("@MortgageAmount", dataGridView1.Rows[c].Cells["MortgageAmount"].Value);
                    upMort.Parameters.AddWithValue("@InterestRate", dataGridView1.Rows[c].Cells["InterestRate"].Value);
                    upMort.Parameters.AddWithValue("@InterestTerm", dataGridView1.Rows[c].Cells["InterestTerm"].Value);                   
                    try
                    {
                        upMort.ExecuteNonQuery();
                    }
                    catch (SqlException ex)
                    {
                        MessageBox.Show(ex.Message );
                    }
             }

                //cmd1.Parameters.AddWithValue("@ClientID" = IDList.SelectedItem;
                //cmd1.Parameters.AddWithValue("@Name", NameTxt.Text.Trim());
                //cmd1.Parameters.AddWithValue("@Street", StreetTxt.Text.Trim());
                //cmd1.Parameters.AddWithValue("@City", CityTxt.Text.Trim());
                //cmd1.Parameters.AddWithValue("@Province", ProvinceTxt.Text.Trim());
                //cmd1.Parameters.AddWithValue("@Postal", PostalTxt.Text.Trim());
                //cmd1.Parameters.AddWithValue("@Phone", PhoneTxt.Text.Trim());
                //cmd1.Parameters.AddWithValue("@Picture", imageData);


                //cmd1.ExecuteNonQuery();

                //catch (SqlException ex)
                //{
                //    MessageBox.Show(ex.Message );
                //}

                //string sql = @"Select Mortgage.ClientID, MortgageAmount, InterestRate,TnterestTerm from Mortgage join ClientIfo on Mortgage.ClientID = ClientInfo.ClientID where ClientInfo.ClientID '" + IDList.SelectedItem + "'";
                //SqlDataAdapter da = new SqlDataAdapter(sql, con);
                ////SqlCommandBuilder cmdBuild = new SqlCommandBuilder(da);
                //DataSet dsup = new DataSet();

                ////DataTable dt1 = new DataTable();
                //da.Fill(dsup,"Mortgage");
                //dataGridView1.DataSource = dsup.Tables["Mortgage"]; ;
                //dsup.Tables["Mortgage"].AcceptChanges();
                //try
                //{
                //    //da.AcceptChangesDuringUpdate = true;
                //    da.Update(dsup,"Mortgage");
                //    DataGridViewRow item = new DataGridViewRow();
                //    dataGridView1.AllowUserToAddRows = true;
                //    item.CreateCells(dataGridView1 );
                //}
                //catch (SqlException ex)
                //{
                //    MessageBox.Show(ex.Message);
                //}
                con.Close();
                RegisForm rg = new RegisForm();
                rg.Show();
                this.Close();

            }
       
        //long m_lImageFileLength;
        //byte[] m_barrImg;
        private void UploadBtn_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "ImageFiles(*.jpg;*jpeg;*.gif;*.bmp)|*.jpg;*jpeg;*.gif;*.bmp";
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
                PathTxt.Text = openFileDialog1.FileName;

            }
            //try
            //{
            //    openFileDialog1.ShowDialog(this);
            //    string strFn = openFileDialog1.FileName;

            //    this.pictureBox1.Image = Image.FromFile(strFn);
            //    FileInfo fiImage = new FileInfo(strFn);

            //    m_lImageFileLength = fiImage.Length;
            //    FileStream fs = new FileStream(strFn, FileMode.Open,
            //                      FileAccess.Read, FileShare.Read);

            //    m_barrImg = new byte[Convert.ToInt32(this.m_lImageFileLength)];
            //    int iBytesRead = fs.Read(m_barrImg, 0,
            //                     Convert.ToInt32(this.m_lImageFileLength));
            //    fs.Close();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }

        private void NameTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (!(e.KeyValue > 58 || e.KeyValue < 49))
            {
                MessageBox.Show("Please Enter text only!");
                CityTxt.Text = "";
                CityTxt.Focus();
            }
        }

        private void CityTxt_KeyDown(object sender, KeyEventArgs e)
        {
            if (!(e.KeyValue > 58 || e.KeyValue < 49))
            {
                MessageBox.Show("Please Enter text only!");
                CityTxt.Text = "";
                CityTxt.Focus();
            }
        }

        private void DeleteBtn_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=L119-N-SMS006;Initial Catalog=MortgageSystem;Integrated Security=True ; MultipleActiveResultSets = true");
           
            string delClient = @"Delete from ClientInfo where ClientID = '" + IDList.SelectedItem + "'";
           
            try
            {              
                SqlCommand delcmd = new SqlCommand(delClient,con);
                con.Open();
                delcmd.ExecuteNonQuery();
                MessageBox.Show("Record Deleted");
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
            }
           
        }

        private void RegisForm_Activated(object sender, EventArgs e)
        {
           
        }

       
    }
}


Creating cash register using WPF


Cash Register GUI, Implement Solution for this.


Add full functionality to the cash register GUI
·         Accept a valid decimal number
·         Enter : adds the value to subtotal
·         Total : calculate 13% HST and present Tax and Total
·         Delete : Deletes value field
·         Clear : empty register.



XAML Code:-

<Window x:Class="Vdesai_Assign1A.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Cash Register" Height="384" Width="465" KeyDown="PreviewkeyDown" Loaded="Window_Loaded" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" SizeToContent="Manual" ResizeMode="CanResize">
    <Window.Resources>
        <Style x:Key="VStyle" TargetType="Button">
            <Setter Property="FontSize" Value="42" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="ButtonBorder"
                  CornerRadius="25,25,25,25"
                  BorderThickness="4,4,4,4"
                  Background="CadetBlue"  
                  BorderBrush="MediumAquamarine"
                  RenderTransformOrigin="0.5,0.5">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*"/>
                                    <RowDefinition Height="1.7*"/>
                                </Grid.RowDefinitions>
                                <Border Grid.Row="0" CornerRadius="23,23,0,0">
                                    <Border.Background>
                                        <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                                            <GradientStop Color="CadetBlue" Offset="0"/>
                                            <GradientStop Color="MediumAquamarine" Offset="1"/>
                                        </LinearGradientBrush>
                                    </Border.Background>
                                </Border>
                                <ContentPresenter x:Name="ButtonContentPresenter"
                                VerticalAlignment="Center" 
                                Grid.RowSpan="2"
                                HorizontalAlignment="Center"/>
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsPressed" Value="True">
                                <Setter Property="RenderTransform" TargetName="ButtonBorder">
                                    <Setter.Value>
                                        <TransformGroup>
                                            <ScaleTransform ScaleX="0.9" ScaleY="0.9"/>
                                        </TransformGroup>
                                  </Setter.Value>
                                </Setter>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="Width" Value="100"/>
                <Setter Property="Height" Value="30"/>
                <Setter Property="Margin" Value="2"/>
            </Style>
    </Window.Resources >
    <Window.Background>
        <LinearGradientBrush SpreadMethod="Reflect">
            <GradientStop Color="Beige"      Offset="0"/>
            <GradientStop Color="CadetBlue"    Offset="1"/>
        </LinearGradientBrush >
    </Window.Background >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="58*" />
            <RowDefinition Height="169.624*" />
            <RowDefinition Height="118.376*" />
        </Grid.RowDefinitions>
        <Label Height="28" HorizontalAlignment="Left" Margin="57,10,0,0" Name="label1" VerticalAlignment="Top" Width="39" Grid.RowSpan="2" Grid.Row="0">
            <Label.Effect>
                <DropShadowEffect ShadowDepth ="5" BlurRadius="5 "/>
            </Label.Effect > "$"
        </Label>
        <TextBox Margin="86,12,77,0" Name="textBox1" KeyDown="textBox1_KeyDown" PreviewTextInput="Preview_TextInput" Height="34" VerticalAlignment="Top" Grid.Row="0"/>
      <UniformGrid Rows ="4" Grid.Row="1" Margin="5,5,204,5">
            <Button Name="OneBtn" Content="1" Margin="5" Click="NumberBtn"  Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18" />
            <Button Name="TwoBtn" Content="2" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18" />
            <Button Name="ThreeBtn" Content="3" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="FourBtn" Content="4" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="FiveBtn" Content="5" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="SixBtn" Content="6" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="SeveBtn" Content="7" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="EightBtn" Content="8" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="NineBtn" Content="9" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="EmptyBtn" Content=" " Margin="5" Visibility="Hidden" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="ZeroBtn" Content="0" Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
            <Button Name="DotBtn" Content="." Margin="5" Click="NumberBtn" Style="{StaticResource VStyle}" Height="29.124" Width="65" FontSize="18"/>
        </UniformGrid>
       
       
        <StackPanel HorizontalAlignment="Right"  Name="stackPanel1"  Orientation="Vertical" Grid.Row="1" Width="144.167" Margin="5">
            <Button Name="EnterBtn" Content="Enter" Style="{StaticResource VStyle}" Click="EnterBtn_Click"  Margin="5"  FontSize="18" />
            <Button Content="Total" Style="{StaticResource VStyle}" Click ="TotalBtn_Click" Margin="5" FontSize="18" />
            <Button  Name="DeleteBtn" Content="Delete" Style="{StaticResource VStyle}" Click ="DeleteBtn_Click" Margin="5" FontSize="18" />
            <Button Content="Clear" Style="{StaticResource VStyle}" Click ="ClearBtn_Click" Margin="5" FontSize="18" />
        </StackPanel >
        <UniformGrid  Name="uniformGrid1" VerticalAlignment="Bottom" Grid.Row="2"  >
            <Label Name="SubtotLbl" Content="Sub Total" Grid.Row="0" Grid.Column="0" FontSize="12" />
            <Label Name="Lbl1" Grid.Row="0" Grid.Column="1" FlowDirection="RightToLeft">
                <Label.Effect>
                    <DropShadowEffect ShadowDepth ="5" BlurRadius="5 "/>
                </Label.Effect > "$"
            </Label>
            <TextBox Name="SubTxt" Grid.Row="0" Grid.Column="2" Width="140.666" />
            <Label Name="TaxLbl" Content="Tax(13%HST+PresentTax)" Grid.Row="1" Grid.Column="0" FontSize="12" Height="29.605" Width="176" />
            <Label Name="Lbl2"  FlowDirection="RightToLeft" Grid.Row="1" Grid.Column="1" >
                <Label.Effect>
                    <DropShadowEffect ShadowDepth ="5" BlurRadius="5 "/>
                </Label.Effect > "$"
            </Label>
            <TextBox Name="TaxTxt" Grid.Row="2" Grid.Column="3" Height="35.5" Width="140.666" />
            <Label Name="TotalLbl" Content="Total" Grid.Row="2" Grid.Column="0"/>          
            <Label Name="Lbl3" FlowDirection="RightToLeft" Grid.Row="2" Grid.Column="1">
                <Label.Effect>
                    <DropShadowEffect ShadowDepth ="5" BlurRadius="5 "/>
                </Label.Effect > "$"
            </Label>
            <TextBox Name="TotTxt" Grid.Row="2" Grid.Column="3" Height="35.5" Width="140.666" />
        </UniformGrid>
    </Grid>
</Window>


Code Behind:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 Vdesai_Assign1A
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        int count = 0;
        public Window1()
        {
            InitializeComponent();
        }
        private void NumberBtn(object sender, RoutedEventArgs e)
        {
            if (((Button)e.OriginalSource).Content.ToString() == ".")
            {
                if (!(textBox1.Text.Contains(".")))
                {
                    textBox1.Text += ((Button)e.OriginalSource).Content.ToString();
                }
                else
                {
                    MessageBox.Show("Input String Not in correct format");
                }
                Keyboard.Focus(textBox1);
            }
            else
                textBox1.Text += ((Button)e.OriginalSource).Content.ToString();
            Keyboard.Focus(textBox1);
        }

        private void EnterBtn_Click(object sender, RoutedEventArgs e)
        {

            if (SubTxt.Text == string.Empty)
            {
                SubTxt.Text = textBox1.Text;
                textBox1.Text = string.Empty;

            }
            else
            {
                decimal a;
                a = Convert.ToDecimal(textBox1.Text);
                decimal b;
                b = Convert.ToDecimal(SubTxt.Text);
                decimal c;
                c = a + b;
                textBox1.Text = string.Empty;
                SubTxt.Text = c.ToString("0.00");
                //                Keyboard .Focus ()
            }
            Keyboard.Focus(textBox1);
        }

        private void TotalBtn_Click(object sender, RoutedEventArgs e)
        {
            decimal tot = Convert.ToDecimal(SubTxt.Text);
            TaxTxt.Text = (((tot) * 13 / 100) + ((tot) * 5 / 100)).ToString();
            decimal tax = Convert.ToDecimal(TaxTxt.Text);
            TotTxt.Text = (tot + tax).ToString();
            Keyboard.Focus(textBox1);
        }

        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Text = string.Empty;
            Keyboard.Focus(textBox1);
        }

        private void ClearBtn_Click(object sender, RoutedEventArgs e)
        {
            textBox1.Text = string.Empty;
            SubTxt.Text = string.Empty;
            TaxTxt.Text = string.Empty;
            TotTxt.Text = string.Empty;
            Keyboard.Focus(textBox1);
        }

        private void PreviewkeyDown(object sender, KeyEventArgs e)
        {
            bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal;
            bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod;

            if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers != ModifierKeys.None)
            {
                e.Handled = true;
                return;
            }

            bool isControl = ((Keyboard.Modifiers != ModifierKeys.None && Keyboard.Modifiers != ModifierKeys.Shift)
                || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert
                || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up
                || e.Key == Key.Tab
                || e.Key == Key.PageDown || e.Key == Key.PageUp
                || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape
                || e.Key == Key.Home || e.Key == Key.End);

            e.Handled = !isControl && !isNumeric && !isNumPadNumeric;

        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal;
            bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod;

            if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers != ModifierKeys.None)
            {
                if ((e.Key == Key.Decimal) && (e.Key == Key.Enter))
                {
                    if (textBox1.Text.Contains("."))
                    {
                        MessageBox.Show("Input String not in correct format");
                    }
                }

                e.Handled = true;
                return;
            }


            else if (e.Key == Key.Enter)
            {
                if (textBox1.Text.Contains("."))
                {

                }
                EnterBtn.Focus();
                if (SubTxt.Text == string.Empty)
                {
                    SubTxt.Text = textBox1.Text;
                    textBox1.Text = string.Empty;
                }
                else
                {
                    decimal a;
                    a = Convert.ToDecimal(textBox1.Text);
                    decimal b;
                    b = Convert.ToDecimal(SubTxt.Text);
                    decimal c;
                    c = a + b;
                    textBox1.Text = string.Empty;
                    SubTxt.Text = c.ToString("0.00");
                }
                Keyboard.Focus(textBox1);
            }
            bool isControl = ((Keyboard.Modifiers != ModifierKeys.None && Keyboard.Modifiers != ModifierKeys.Shift)
                || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert
                || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up
                || e.Key == Key.Tab
                || e.Key == Key.PageDown || e.Key == Key.PageUp
                || e.Key == Key.Return || e.Key == Key.Escape
                || e.Key == Key.Home || e.Key == Key.End);

            e.Handled = !isControl && !isNumeric && !isNumPadNumeric;

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(textBox1);
        }

        private void Preview_TextInput(object sender, TextCompositionEventArgs e)
        {
            foreach (char ch in e.Text)
            {
                if (e.Text.Contains('.')) count++;
                if (count <= 1)
                {
                    if (!(Char.IsDigit(ch) || ch.Equals('.')))
                        e.Handled = true;
                }
                else
                    if (!(Char.IsDigit(ch)))
                        e.Handled = true;
            }
        }
    }
}