.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Melody Anderson

Home >> Code Snippets >> ADO.NET >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Inserting Values in Database

Posted By:Abhisek Panda       Posted Date: October 26, 2009    Points: 10    Category: ADO.NET    URL: http://www.dotnetspark.com  

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");





Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend