In this article I will explain with an example, how to use SCOPE_IDENTITY with ADO.Net in ASP.Net using C# and VB.Net.
I have made use of the following table Customers with the schema as follows.
Using SCOPE_IDENTITY with ADO.Net in ASP.Net
Note: You can download the database table SQL by clicking the download link below.
         Download SQL file
HTML Markup
The HTML Markup consists of:
TextBox – For inputting Name and Country.
Button – For submitting the Form.
        <td><asp:TextBox ID="txtName" runat="server" /></td>
        <td><asp:TextBox ID="txtCountry" runat="server" /></td>
        <td><asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" /></td>
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
Imports System.Configuration
Imports System.Data.SqlClient
Inserting record in Database in ASP.Net
When the Submit Button is clicked, following event handler is executed.
Inside this event handler, the name value is fetched from the TextBox, while and the country value is fetched from the DropDownList and are inserted into the SQL Server database table using ADO.Net.
Finally, the CustomerId of the inserted record is fetched and displayed in JavaScript Alert Message Box using RegisterStartupScript method.
protected void Submit(object sender, EventArgs e)
    int customerId;
    string query = "INSERT INTO Customers(Name, Country) VALUES(@Name, @Country)";
    query += " SELECT SCOPE_IDENTITY()";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
        using (SqlCommand cmd = new SqlCommand(query))
            cmd.Parameters.AddWithValue("@Name", txtName.Text);
            cmd.Connection = con;
            customerId = Convert.ToInt32(cmd.ExecuteScalar());
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Inserted Customer ID: " + customerId + "');", true);
Protected Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
    Dim customerId As Integer
    Dim query As String = "INSERT INTO Customers(Name, Country) VALUES(@Name, @Country)"
    query += " SELECT SCOPE_IDENTITY()"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.Parameters.AddWithValue("@Name", txtName.Text)
            cmd.Parameters.AddWithValue("@Country", txtCountry.Text)
            cmd.Connection = con
            customerId = Convert.ToInt32(cmd.ExecuteScalar())
        End Using
    End Using
    ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Inserted Customer ID: " & customerId & "');", True)
End Sub
The Form
Using SCOPE_IDENTITY with ADO.Net in ASP.Net
Record after Insert in database
Using SCOPE_IDENTITY with ADO.Net in ASP.Net