SIGN UP MEMBER LOGIN:    
ARTICLE

Inserting & Retrieving records from MS Excel 2003 using OLEDB

Posted by Prashanth Chindam Articles | ADO.NET in C# October 29, 2010
In this article we will see how to develop a windows application using C#.Net to insert, search and update records from M.S.Excel-2003 file using OleDb Connection.
Reader Level:
Download Files:
 

Objective:

To develop a windows application using C#.Net to insert, search and update records from M.S.Excel-2003 file using OleDb Connection.

Design:

1.gif

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

Introduction:

As we want to use OleDb Connection include the namespace: 'using System.Data.OleDb'

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

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

Adding Reference to Microsoft.VisualBasic:

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 since we don't have any primarykey column in M.S.Excel 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 for a record, we have to get the index of that record so that we can navigate the next and previous records.

Eg:

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

Code:

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

namespace xloledb03
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        OleDbConnection con;
        OleDbCommand cmd;
        OleDbDataAdapter da;
        DataSet ds;
        int rno = 0;  
        private void Form1_Load(object sender, EventArgs e)
        {
            con = new OleDbConnection(@"Provider=Microsoft.Jet.Oledb.4.0;data source=E:\prash\xldb.xls;Extended Properties=""Excel 8.0;HDR=Yes;"" ");
            //xldb.xls ->MS.Excel-2003 file, hdr=yes-> 1st row is treated as header
            loaddata();
            showdata();  
        }
        void loaddata()
        {
            da = new OleDbDataAdapter("select * from [student$]", con);
            //student-> sheet name in xldb.xls file, which should be specified as [student$]
            ds = new DataSet();
            da.Fill(ds, "student");
            ds.Tables[0].Constraints.Add("pk_sno", ds.Tables[0].Columns[0], true);
            //creating primary key in Tables["student"] of dataset(for using Find() method)
            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 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)
            {
                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 btnFirst_Click(object sender, EventArgs e)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                rno = 0;
                showdata();
                MessageBox.Show("First Record");
            }
            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();
                MessageBox.Show("Last Record");
            }
            else
                MessageBox.Show("no records");
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox2.Text = textBox3.Text = "";
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Note: 'xldb.xls' file is provided in xloledb03.zip file along with source code.

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

Awesome content...which will be really benificial.

Posted by KRISHNA KANT Mar 19, 2012

hey prashanth i want some more examples with oledb and in c# not in VB

Posted by parth khatwani Jan 26, 2012

Thanks bhai for uploading such use full information , i want to do the same thing in C# Web application would you please guide how to retrieve the image in grid and when some one clicks the image it enlarges Automatically to its original size. here is my email address if you could help me doing this the stored images are in binary format. khalidy5@live.com

Posted by Abdul Baseer Yousofza Nov 01, 2011

Thanks

~Ur's Prashanth.Chindam

Posted by Prashanth Chindam Oct 30, 2010

Agreed with other two guys!

Posted by Mahesh Chand Oct 30, 2010
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    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. Visit DynamicPDF here
Become a Sponsor