Inserting values in MSAccess Database using windows Application

Syedshakeer
Posted by Syedshakeer under C# category on | Views : 7189
How to insert a Record in MS Aceess database using Windows Aplplication

add one Button and two tetboxes on Windows Form and give names for textboxes as textrollno and textname

1)First Open Ms Access Database and create a Table with two columns as rollno and name.
2)set a DataSourceName(dsn) for a table

if we using MS Access DataBase we have to add a NameSpace as
using System.Data.OdbcClient


3)conecct to your ms access database using dataSourcename(dsn)

OdbcConnection conn=new OdbcConnection("dsn=sourcename");

4)Open a Connection with a connection object as follows

conn.Open();
5)use OdbcCommand class to inserting values and pass insert command query and connection obect as arguments in OdbcCommand Class as follows

OdbcCommand cmd=new OdbcCommand("insert into tablename (rollno,name) values("+textrollno.Text+",'"+name+"')",conn);

6)Next write a ExecuteNonQuery() with a OdbcCommand object as follows

cmd.ExecuteNonQuery();

7)Note:if your using Insert,Update,Delete,Create commands then you have to use ExecuteNonQuery() mehtod with a object of OdbcCommand class

Total Programming code is Below
------------------------------------------------------------------------------

using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.OdbcClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
OdbcConnection conn=new OdbcConnection("dsn=sourcename");
conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
OdbcCommand cmd=new OdbcCommand("insert into tablename (rollno,name) values("+textrollno.Text+",'"+name+"')",conn);

cmd.ExecuteNonQuery();

MessageBox.Show("One Inserted Sucessfully");

}
}

Comments or Responses

Login to post response