Monday, 19 August 2013

How to insert data into Ms Access 2007 using WPF



Xaml.Cs Code :

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
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 SampleWpfApp
{
    public partial class MainWindow : Window
    {
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\WPFDatabase.accdb");
        public MainWindow()
        {
            InitializeComponent();
            Bind();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            con.Open();
            OleDbCommand cmd = new OleDbCommand("BankTableInsert", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@BankName", cmbBankName.SelectedIndex);
            cmd.Parameters.AddWithValue("@AccountNo", txtAcNo.Text);
            if (rbtnSavingsAc.IsChecked.Value)
            {
                cmd.Parameters.AddWithValue("@AccountType", rbtnSavingsAc.Content);
            }
            else if (rbtnCurrentAc.IsChecked.Value)
            {
                cmd.Parameters.AddWithValue("@AccountType", rbtnCurrentAc.Content);
            }
            else if (rbtnCreditCard.IsChecked.Value)
            {
                cmd.Parameters.AddWithValue("@AccountType", rbtnCreditCard.Content);
            }
            else
            {
                cmd.Parameters.AddWithValue("@AccountType", rbtnOther.Content);
            }


            cmd.Parameters.AddWithValue("@Balance", txtBalance.Text);
            cmd.Parameters.AddWithValue("@Date", System.DateTime.Now.ToShortDateString());

           int result = cmd.ExecuteNonQuery();
           con.Close();
            if (result > 0)
            {
                MessageBox.Show("Record inserted successfully");
            }
            else
            {
                MessageBox.Show("Error occured, please try again", "Alert");
            }
            Bind();
        }

        private void Bind()
        {

            con.Open();
            OleDbDataAdapter da = new OleDbDataAdapter("select * from BankTable”, con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            BanksetupGrid.ItemsSource = dt.DefaultView;
            con.Close();   
        }  
    }
}




OutPut:


No comments:

Post a Comment