• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 254
  • Last Modified:

c# msaccess return newly inserted rows id


I have a networked database, with a number of users

I have a situation where I need to insert a record into a table, and return the autonumber ID generated by access, so that the user can add records to another table using the id from the first table as the foreign key.

I have used the following sql statement

"Select @@Identity from " + table;

which works most times, however on the odd occasion it appears to be returning either nothing or the id from the previous record.

Is there any way to ensure that the query returns the correct value each time?

here is my code to insert data

  public int InsertData(string table, string[] fields, string[] values)
            int id = 0;
            OleDbConnection con = new OleDbConnection(connectionstring);
            string query2 = "Select @@Identity from " + table;
            string myFields = "";
            string myValues = "";

            foreach (string f in fields)
                myFields += f + ", ";
                myValues += "?,";


            if (myFields.Length > 0)
                myFields = myFields.Substring(0, myFields.Length - 2);
                myValues = myValues.Substring(0, myValues.Length - 1);

            OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("INSERT INTO " + table + " (" + myFields + ") Values (" + myValues + ") ", con);

            foreach (string v in values)

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = query2;
            id = Convert.ToInt32(cmd.ExecuteScalar());

            return id; 

Open in new window

  • 3
2 Solutions
Fernando SotoRetiredCommented:
Hi cycledude;

According to this Microsoft article you will need two OleDbCommand connections. The article shows how to do this.

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

Any ideas how I can get that to work with my code?
cycledudeAuthor Commented:
in the end I had to use a timestamp when entering the row, then use a while loop to repeat the process of acquiring the id every 1 second until the correct id was found.
cycledudeAuthor Commented:
thanks for the assist
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Easily Design & Build Your Next Website

Squarespace’s all-in-one platform gives you everything you need to express yourself creatively online, whether it is with a domain, website, or online store. Get started with your free trial today, and when ready, take 10% off your first purchase with offer code 'EXPERTS'.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now