Tuesday, 21 August 2012

How to insert data into Ms Access 2007 using WPF || Inserting and Binding of data to GridView from Ms Access in WPF

Xamal.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

CRUD operations using AngularJS in Asp.Net MVC

In this article I will show you how to perform CRUD operations in Asp.Net MVC5 using AngularJS. Add AngularJS using the Manage Nuget Pack...