Get Latest Inserted ID from datatbase Using @@Identity in csharp

26/04/2017   10:46:58 AM

Hello,in this c# tutorial i will explain how to select and display latest or last Inserted ID from datatbase table using @@Identity in csharp.but after execute insert statement before closing connection must to add @@Identity to get last inserted id value.

1 .Create database name as Test. Create a Table name as EmployeeDtls in this database.

Column Name

DataTypes

EmpId

Int [Identity Property Set =True]

EmpName

varchar(50)

 

2. Open VisualStudio.Net / Select C# / Windows Application

 

3. Make the design of the form as Follows.

 

4.Add the following code on save and get id button click event btnSave_Click

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace GetLatestId
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True");
private void btnSave_Click(object sender, EventArgs e)
{
SqlCommand cmdinsert = new SqlCommand("Insert INTO EmployeeDtls Values(@EmpName)", con);
cmdinsert.CommandType = CommandType.Text;
cmdinsert.Parameters.AddWithValue("@EmpName", txtxName.Text);
con.Open();
cmdinsert.ExecuteNonQuery();
SqlCommand cmdselect = new SqlCommand("Select @@identity", con);
txtId.Text = cmdselect.ExecuteScalar().ToString();
con.Close();
}
}
}

Output

                   

Support us by Sharing