Inserting values in Database

Posted by Abhisek under C# category on | Views : 1952
Description :

First you have to create a simple database in access with only one table(Student) containing fields sname and sroll. Then save it and close it.

Now design a form to provide the user an interface to store data. The form contains two labels(Name, Roll) and two text boxes representing name and roll. Here the name of the text boxes are txtName and txtRoll.

Also add a button "Save" to the form and change its name to btnSave. Clicking on this button will save the value we are passing inside the textboxes into the database table.

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

namespace InsertData
public partial class Form1 : Form
//creating instances of Command and Connection class
OleDbCommand cmd;
OleDbConnection con;
public Form1()
private void btnSave_Click(Object Sender,EventArgs e)
int c;
this.con = new OleDbConnection();
//passing the database path and provider name
this.con.ConnectionString = "Data Source = d:\\Student.mdb;Provider = Microsoft.Jet.Oledb4.0";
this.cmd = new OleDbCommand();
this.cmd.Connection = this.con;
this.cmd.CommandType = CommandType.Text;
//passing insert command to insert values into the database table
this.cmd.CommandText = "insert into Student values('" + this.txtName.Text"' + '"this.txtRoll.Text + "')";
this.con = open();
//checking whether command successfully executed
c = this.cmd.ExecuteNonQuery();
if(c > 0)
MessageBox.Show("Record inserted");
this.txtName.Text = " ";
this.txtRoll.Text = " ";
MessageBox.Show("Record not saved");

Comments or Responses

Login to post response