SIGN UP MEMBER LOGIN:    
ARTICLE

Creating & Retrieving records from M.S.Access-2007 using Oledb in C#.net

Posted by Prashanth Chindam Articles | ADO.NET in C# October 04, 2010
In this article you will learn how to create & retrieve records from M.S.Access-2007 using Oledb in C#.net.
Reader Level:
Download Files:
 


Design:

msaccess07.JPG

Design the form as above with a DataGridView, 3 Labels, 3 TextBoxes, 10 buttons.

Note: In order to perform operations on M.S.Access-2007 records, M.S.Office-2007 should be installed in your system.

Introduction:

As we want to use OleDb Connection include the namespace:

'using System.Data.OleDb'

For accesing records from M.S.Access-2003 file we use 'Jet' driver,

But for accesing records from M.S.Access-2007 file we use 'Ace' driver.

In this application, we will search a record by taking input from the InputBox. For this we have to add reference to Microsoft.VisualBasic.

Adding a Reference:

Goto Project Menu ->Add Reference -> select 'Microsoft.VisualBasic' from .NET tab.

In order to use this we have to include the namespace:

'using Microsoft.VisualBasic'

Creating a primary key in the dataTable:

In this app. we use Find() method to search a record, which requires details of primarykey column for database tables; this is provided using statement: adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey

But as we don't have any primarykey column in M.S.Access table, we have to create a primary key column in datatable.

Eg:

ds.Tables[0].Constraints.Add("pk_sno", ds.Tables[0].Columns[0], true);

Pointing to current record in dataTable:

After searching a record, we have to get the index of that record so that we can show next and previous records when we press '>>'(next) and '<<'(previous) buttons.

Eg:

rno= ds.Tables[0].Rows.IndexOf(drow);
-------------
Code:

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
using Microsoft.VisualBasic;

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

        OleDbConnection con;
        OleDbCommand cmd;
        OleDbDataAdapter adapter;
        DataSet ds;
        int rno;

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new OleDbConnection(@" provider=Microsoft.ace.Oledb.12.0; data
source=E:\prash\stud.accdb;Persist Security Info=False"
);//stud.accdb->access07 filename
            loaddata();
            showdata();
        }
        void loaddata()
        {
            adapter = new OleDbDataAdapter("select * from student", con);
            ds = new DataSet();//student-> table name in stud.accdb file
            adapter.Fill(ds, "student");
            ds.Tables[0].Constraints.Add("pk_sno", ds.Tables[0].Columns[0], true);//creating
primary key for Tables[0] in dataset
            dataGridView1.DataSource = ds.Tables[0];
        }
        void showdata()
        {
            textBox1.Text = ds.Tables[0].Rows[rno][0].ToString();
            textBox2.Text = ds.Tables[0].Rows[rno][1].ToString();
            textBox3.Text = ds.Tables[0].Rows[rno][2].ToString();
        }
     
        private void btnFirst_Click(object sender, EventArgs e)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                rno = 0;
                showdata();
            }
            else
                MessageBox.Show("no records");
        }
 
        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (rno > 0)
                {
                    rno--;
                    showdata();
                }
                else
                    MessageBox.Show("First Record");
            }
            else
                MessageBox.Show("no records");
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (rno < ds.Tables[0].Rows.Count - 1)
                {
                    rno++;
                    showdata();
                }
                else
                    MessageBox.Show("Last Record");
 
            }
            else
                MessageBox.Show("no records");
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                rno = ds.Tables[0].Rows.Count - 1;
                showdata();
            }
            else
                MessageBox.Show("no records");
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            cmd = new OleDbCommand("insert into student values(" + textBox1.Text + ",' " + textBox2.Text + " ',' " + textBox3.Text + " ')", con);
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();

            if (n > 0)
            {
                MessageBox.Show("record inserted");
                loaddata();
            }
            else
                MessageBox.Show("insertion failed");
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            int n = Convert.ToInt32(Interaction.InputBox("Enter sno:", "Search", "20", 200, 200)
;
            DataRow drow = ds.Tables[0].Rows.Find(n);
            if (drow != null)
            {
                rno = ds.Tables[0].Rows.IndexOf(drow);
                textBox1.Text = drow[0].ToString();
                textBox2.Text = drow[1].ToString();
                textBox3.Text = drow[2].ToString();
            }
            else
                MessageBox.Show("Record not found");
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            cmd = new OleDbCommand("update student set sname='" + textBox2.Text + "',course='" + textBox3.Text + "' where sno=" + textBox1.Text, con);
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();
            if (n > 0)
            {
                MessageBox.Show("Record Updated");
                loaddata();
            }
            else
                MessageBox.Show("Update failed");
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            cmd = new OleDbCommand("delete from student where sno=" + textBox1.Text, con);
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();
            if (n > 0)
            {
                MessageBox.Show("Record Deleted");
                loaddata();
            }

            else
                MessageBox.Show("Deletion failed");
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox2.Text = textBox3.Text = "";
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

Login to add your contents and source code to this article
share this article :
post comment
 

post a code in C#.net this is a vb code

Posted by parth khatwani Jan 26, 2012

Thanks for Ur feedback

Posted by Prashanth Chindam Feb 08, 2011

Hi, I'd like to thank you for the very good and useful tutorial. I'm beginner in this theme but it was very helpful to me! I searched a lot of time while find this!

Posted by martin popov Feb 03, 2011

*searching a record based on 'sname':

DataRow drow = ds.Tables[0].Rows.Select("sname"=<sname>);
eg: DataRow drow = ds.Tables[0].Rows.Select("sname"='prashanth');
-it will select multiple rows matching with that 'sname'

->to select single record based on 'sname:
DataRow drow = ds.Tables[0].Rows.Select("sname"=<sname>)[0];
-it will select first row matching with that 'sname'

Note:
'Select()' method can be used to find records with non primarykey filled data, it returns multiple records matching with the expression (array of DataRows).

-Thanks for Ur feedback
~ Ur's Prashanth.Chindam

Posted by Prashanth Chindam Oct 07, 2010

1. Make sure that M.SOffice-2007  is installed in your system.

2. *Check that connection string is written correctly.
ex:
con = new OleDbConnection(@" provider=Microsoft.Ace.Oledb.12.0; data source=E:\prash\stud.accdb;Persist Security Info=False");

3. *Be aware of spaces
for example, if the same connection string is written as:

con = new OleDbConnection(@" provider=Microsoft.Ace.Oledb.12.0; data source=E:\prash\stud.accdb;Persist SecurityInfo=False");

->It will throw an error 'could not found installable ISAM'.
Here, the cause of the error is the lack of space between words 'Security' and 'Info' i.e, ' Persist SecurityInfo=False'
-----------------------

->suggestion:
copy the 'prash_access07.zip' file (source code) from the article
'Creating & Retrieving records from M.S.Access-2007 using Oledb in C#.net ',
extract it and copy the 'stud.accdb' (M.S.Access2007 document )  present in the extracted folder, place it in your desired location and specify that path in the 'data source' of connection string.

ex:
replace the path 'E:\prash\stud.accdb'  'data source=E:\prash\stud.accdb' with the path of your M.S.Access2007 file

-Thanks for Ur feedback
~ Ur's Prashanth.Chindam

Posted by Prashanth Chindam Oct 07, 2010
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor