Microsoft Knowledge Base Email Alertz

KBAlertz.com: (816112) - This step-by-step article discusses how to retrieve the identity column value from an Access database. Retrieving the Identity value from a Jet database is different from that of SQL Server, because a Jet database does not support multi-statement...

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 2.0 Web Hosting with SQL 2005: Click Here!
Discount ASP.NET Hosting


Bug Tracking Software
For bug tracking software or defect tracking software or issue tracking software, visit Axosoft.


Community Site



We Send hundreds of thousands of emails using ASP.NET Email



Expert Web Design & Graphic Design
Design44.com




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




HOW TO: Retrieve the Identity Value While Inserting Records into Access Database By Using Visual C# .NET

Article ID:816112
Last Review:May 12, 2007
Revision:1.2
On This Page

SUMMARY

This step-by-step article discusses how to retrieve the identity column value from an Access database.

Retrieving the Identity value from a Jet database is different from that of SQL Server, because a Jet database does not support multi-statement batch commands. The Jet OLE DB Provider version 4.0 supports the SELECT @@Identity query that allows you to retrieve the value of the auto-increment field that is generated on your connection. To run the SELECT @@Identity query, use another OleDbCommand object. This article describes how to use a second OleDbCommand to retrieve the Identity column value.

Back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
•Microsoft Jet OLE DB Provider version 4.0
•Microsoft Visual C# .NET
This article assumes that you are familiar with the following topics:
•Visual C# .NET programming
•Visual Studio .NET IDE

Back to the top

Connect to the Access Database

To connect to the Access database, and create a table with the Identity column, follow these steps:
1.Start Microsoft Visual Studio .NET 2002.
2.On the File menu, point to New, and then click Project.
3.Under Project Types, click Visual C# Projects, and then under Templates, click Console Application. By default, Class1.cs is created.
4.Name the project MyJetApplication, and then click OK.
5.Replace the existing code with the following code:
using System;
using System.Data;
using System.Data.OleDb;

namespace ConsoleApplication30
{
	class Class1
	{
      [STAThread]
      static void Main(string[] args)
      {
         // Open Connection 
         OleDbConnection cnJetDB = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourAccessDatabase");
         cnJetDB.Open();

         // If the test table does not exist then create the Table
         string strSQL; 
         strSQL = "CREATE TABLE AutoIncrementTest " +
            "(ID int identity, Description varchar(40), " +
            "CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID))";

         // Command for Creating Table
         OleDbCommand cmdJetDB = new OleDbCommand(strSQL, cnJetDB);
         cmdJetDB.ExecuteNonQuery();

         // Create a DataAdaptor With Insert Command For inserting records
         OleDbDataAdapter oleDa = new OleDbDataAdapter("Select * from AutoIncrementTest", cnJetDB);

         // Command to Insert Records
         OleDbCommand cmdInsert = new OleDbCommand();
         cmdInsert.CommandText = "INSERT INTO AutoIncrementTest (Description) VALUES (?)";
         cmdInsert.Connection = cnJetDB;
         cmdInsert.Parameters.Add(new OleDbParameter("Description", OleDbType.VarChar, 40, "Description"));
         oleDa.InsertCommand = cmdInsert;

         // Create a DataTable
         DataTable dtTest = new DataTable();
         oleDa.Fill(dtTest);

         DataRow drTest;

         // Add Rows to the Table
         drTest = dtTest.NewRow();
         drTest["Description"] = "This is a Test Row 1";
         dtTest.Rows.Add(drTest);

         drTest = dtTest.NewRow();
         drTest["Description"] = "This is a Test Row 2";
         dtTest.Rows.Add(drTest);
      }
	}
}
6.Modify the Data Source name in the connection string to point to your Access database.

Back to the top

Trap the Identity Column Value

In the RowUpdated event of the DataAdapter, you can trap the identity column value that is generated for a column of a Table in an Access database. In the RowUpdated event, run the SELECT @@IDENTITY query by using another Command object, and then assign the value that is returned by the query to the Identity column. Call the AcceptChanges method of the DataRow object to accept the column value. To do this, follow these steps:
1.Add the following code before the Main method to create a second OleDbCommand object for the SELECT @@IDENTITY query:
      // Create OleDbCommand for SELECT @@IDENTITY statement
      private static OleDbCommand cmdGetIdentity;
2.Add the following code to the Main method to create a new instance of the OleDbCommand class:
         // Create another Command to get IDENTITY Value
         cmdGetIdentity = new OleDbCommand();
         cmdGetIdentity.CommandText = "SELECT @@IDENTITY";
         cmdGetIdentity.Connection = cnJetDB;
3.Add the following code to Main method to handle the RowUpdated event:
         // Delegate for Handling RowUpdated event
         oleDa.RowUpdated += new OleDbRowUpdatedEventHandler(HandleRowUpdated);
4.Add the following code to the Main method to update the data. The RowUpdated event is raised after calling the Update method:
         // Update the Data
         oleDa.Update(dtTest);
5.Add the following code to Main method to drop the AutoIncrementTest table and release the resources:
         // Drop the table
         cmdJetDB.CommandText = "DROP TABLE AutoIncrementTest";
         cmdJetDB.ExecuteNonQuery();

         // Release the Resources
         cmdGetIdentity = null;
         cmdInsert = null;
         cmdJetDB = null;
         cnJetDB.Close();
         cnJetDB = null;
6.Add the following RowUpdated event handler code to Module1:
      // Event Handler for RowUpdated Event
      private static void HandleRowUpdated(object sender, OleDbRowUpdatedEventArgs e)
      {
         if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert )
         {
            // Get the Identity column value
            e.Row["ID"] = Int32.Parse(cmdGetIdentity.ExecuteScalar().ToString());
            System.Diagnostics.Debug.WriteLine(e.Row["ID"]);
            e.Row.AcceptChanges();
         }
      }
7.On the Debug menu, click Start to run the application. Identity column values are displayed in the Output window.

Back to the top

Complete Code Listing

using System;
using System.Data;
using System.Data.OleDb;

namespace ConsoleApplication30
{
	class Class1
	{
      // Create OleDbCommand for SELECT @@IDENTITY statement
      private static OleDbCommand cmdGetIdentity;

      [STAThread]
      static void Main(string[] args)
      {
         // Open Connection 
         OleDbConnection cnJetDB = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourAccessDatabase");
         cnJetDB.Open();

         // If the test table does not exist then create the Table
         string strSQL; 
         strSQL = "CREATE TABLE AutoIncrementTest " +
            "(ID int identity, Description varchar(40), " +
            "CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID))";

         // Command for Creating Table
         OleDbCommand cmdJetDB = new OleDbCommand(strSQL, cnJetDB);
         cmdJetDB.ExecuteNonQuery();

         // Create a DataAdaptor With Insert Command For inserting records
         OleDbDataAdapter oleDa = new OleDbDataAdapter("Select * from AutoIncrementTest", cnJetDB);


         // Command to Insert Records
         OleDbCommand cmdInsert = new OleDbCommand();
         cmdInsert.CommandText = "INSERT INTO AutoIncrementTest (Description) VALUES (?)";
         cmdInsert.Connection = cnJetDB;
         cmdInsert.Parameters.Add(new OleDbParameter("Description", OleDbType.VarChar, 40, "Description"));
         oleDa.InsertCommand = cmdInsert;

         // Create a DataTable
         DataTable dtTest = new DataTable();
         oleDa.Fill(dtTest);

         DataRow drTest;

         // Add Rows to the Table
         drTest = dtTest.NewRow();
         drTest["Description"] = "This is a Test Row 1";
         dtTest.Rows.Add(drTest);

         drTest = dtTest.NewRow();
         drTest["Description"] = "This is a Test Row 2";
         dtTest.Rows.Add(drTest);

         // Create another Command to get IDENTITY Value
         cmdGetIdentity = new OleDbCommand();
         cmdGetIdentity.CommandText = "SELECT @@IDENTITY";
         cmdGetIdentity.Connection = cnJetDB;

         // Delegate for Handling RowUpdated event
         oleDa.RowUpdated += new OleDbRowUpdatedEventHandler(HandleRowUpdated);

         // Update the Data
         oleDa.Update(dtTest);

         // Drop the table
         cmdJetDB.CommandText = "DROP TABLE AutoIncrementTest";
         cmdJetDB.ExecuteNonQuery();

         // Release the Resources
         cmdGetIdentity = null;
         cmdInsert = null;
         cmdJetDB = null;
         cnJetDB.Close();
         cnJetDB = null;
      }

      // Event Handler for RowUpdated Event
      private static void HandleRowUpdated(object sender, OleDbRowUpdatedEventArgs e)
      {
         if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert )
         {
            // Get the Identity column value
            e.Row["ID"] = Int32.Parse(cmdGetIdentity.ExecuteScalar().ToString());
            System.Diagnostics.Debug.WriteLine(e.Row["ID"]);
            e.Row.AcceptChanges();
         }
      }
	}
}

Back to the top

REFERENCES

For additional information, click the following article number to view the article in the Microsoft Knowledge Base:
232144 (http://kbalertz.com/Feedback.aspx?kbNumber=232144/EN-US/) INFO: Jet OLE DB Provider Version 4.0 Supports SELECT @@Identity
For more information, visit the following Microsoft Developer Network Web site:
OleDbDataAdapter.RowUpdated Event
http://msdn2.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.rowupdated(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.rowupdated(vs.71).aspx)



Back to the top


APPLIES TO
•Microsoft ADO.NET 1.0
•Microsoft Visual C# .NET 2002 Standard Edition

Back to the top

Keywords: 
kbtsql kbjet kbhowtomaster kbhowto kbsystemdata KB816112

Back to the top

       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Chris Norwood Report As Irrelevant  
Written: 6/18/2006 11:49 AM
I struggle for a while to obtain the ID of a newly INSERTed Row (even SELECT @@IDENTITY return NULL). Your code in the method HandleRowUpdated() gave me exactly what I needed. Many Thanks.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please