Search

Sunday, August 23, 2015
0 comments

How to insert item into MS-access database using windows form c#

11:44 PMSunday, August 23, 2015
Introduction
In previous article i explained how to create connection with MS-Access database; How to bind DataGrid with access database. In this article i will teach you how to insert item into Access database using windows form. Lets take a simple example of inserting item into access database.


Description
First of all create connection with the access database which is already done in previous article. Now, you will do some changes in code of  datagrid binding. Like replace DQL query with DML query.

Like :
cmd.CommandText = "Insert into [tablename](columnName)Values(Data)";

Also do not required to execute the query, use ExecuteNonQuery() method to insert data by the input box.

using System;
using System.Configuration;
using System.Data.OleDb;
using System.Windows.Forms;

namespace ConnectAccessDatabase
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString=ConfigurationManager.ConnectionStrings["Connection"].ToString();
            con.Open();

            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandText = "insert into [Employee](Name1)values(@nm)";
            cmd.Parameters.AddWithValue("@nm", textBox1.Text);
            cmd.Connection = con;
            int a = cmd.ExecuteNonQuery();
            if(a>0)
            {
                MessageBox.Show("Inserted");
            }
        }
    }
}

Code generate the following output

How to insert item into MS-access database using windows form c#



Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top