Advertisement
hubert17

Getting the identity of the most recently added record

Oct 12th, 2014
475
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.81 KB | None | 0 0
  1. //C# Access and @@Identity
  2. string query = "Insert Into Categories (CategoryName) Values (?)";
  3. string query2 = "Select @@Identity";
  4. int ID;
  5. string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
  6. using (OleDbConnection conn = new OleDbConnection(connect))
  7. {
  8.   using (OleDbCommand cmd = new OleDbCommand(query, conn))
  9.   {
  10.     cmd.Parameters.AddWithValue("", Category.Text);
  11.     conn.Open();
  12.     cmd.ExecuteNonQuery();
  13.     cmd.CommandText = query2;
  14.     ID = (int)cmd.ExecuteScalar();
  15.   }
  16. }
  17.  
  18. //C# DataSource controls
  19. protected void AccessDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
  20. {
  21.   string query = "SELECT @@IDENTITY";
  22.   OleDbCommand cmd = new OleDbCommand(query, (OleDbConnection)e.Command.Connection);
  23.   int newid = (int)cmd.ExecuteScalar();
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement