Microsoft KB Archive/816112

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

Article ID: 816112

Article Last Modified on 5/12/2007

-

APPLIES TO


 * Microsoft ADO.NET 1.0
 * Microsoft Visual C# .NET 2002 Standard Edition

-





For a Microsoft Visual Basic .NET version of this article, see 815629.

IN THIS TASK

 * SUMMARY
 * Requirements
 * Connect to the Access Database
 * Trap the Identity Column Value
 * Complete Code Listing
 * REFERENCES



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:  Start Microsoft Visual Studio .NET 2002. On the File menu, point to New, and then click Project. Under Project Types, click Visual C# Projects, and then under Templates, click Console Application. By default, Class1.cs is created. Name the project MyJetApplication, and then click OK.  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(@&quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourAccessDatabase&quot;); cnJetDB.Open;

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

// 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(&quot;Select * from AutoIncrementTest&quot;, cnJetDB);

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

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

DataRow drTest;

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

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

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: <ol>  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; </li>  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 = &quot;SELECT @@IDENTITY&quot;; cmdGetIdentity.Connection = cnJetDB; </li>  Add the following code to Main method to handle the RowUpdated event: // Delegate for Handling RowUpdated event oleDa.RowUpdated += new OleDbRowUpdatedEventHandler(HandleRowUpdated); </li>  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); </li>  Add the following code to Main method to drop the AutoIncrementTest table and release the resources: // Drop the table cmdJetDB.CommandText = &quot;DROP TABLE AutoIncrementTest&quot;; cmdJetDB.ExecuteNonQuery;

// Release the Resources cmdGetIdentity = null; cmdInsert = null; cmdJetDB = null; cnJetDB.Close; cnJetDB = null; </li>  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[&quot;ID&quot;] = Int32.Parse(cmdGetIdentity.ExecuteScalar.ToString); System.Diagnostics.Debug.WriteLine(e.Row[&quot;ID&quot;]); e.Row.AcceptChanges; }     } </li> On the Debug menu, click Start to run the application. Identity column values are displayed in the Output window.</li></ol>

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(@&quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourAccessDatabase&quot;); cnJetDB.Open;

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

// 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(&quot;Select * from AutoIncrementTest&quot;, cnJetDB);

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

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

DataRow drTest;

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

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

// Create another Command to get IDENTITY Value cmdGetIdentity = new OleDbCommand; cmdGetIdentity.CommandText = &quot;SELECT @@IDENTITY&quot;; cmdGetIdentity.Connection = cnJetDB;

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

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

// Drop the table cmdJetDB.CommandText = &quot;DROP TABLE AutoIncrementTest&quot;; 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[&quot;ID&quot;] = Int32.Parse(cmdGetIdentity.ExecuteScalar.ToString); System.Diagnostics.Debug.WriteLine(e.Row[&quot;ID&quot;]); e.Row.AcceptChanges; }     }    } } back to the top

<div class="references_section">