Hi nauna,
Usng the below article i have created the example.
Check this example. Now please take its reference and correct your code.
I have used Customers table. CustomerId is an Auto-Increment (Identity) column.
You can download the database table SQL by clicking the download link below.
Download SQL file
SQL
CREATE PROCEDURE [dbo].[AddCustomerReturnIDwithoutput]
@Name varchar(50),
@Country varchar(50),
@id int output
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Customers VALUES (@Name,@Country)
SET @id = SCOPE_IDENTITY()
RETURN @id
END
DataAccess
using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public class DataAccess
{
public DataAccess()
{
}
public int InsertCustomer(string name, string country)
{
int id;
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "AddCustomerReturnIDwithoutput";
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = country;
cmd.Parameters.Add("@id", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
id = Convert.ToInt32(cmd.Parameters["@id"].Value);
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
return id;
}
}
HTML
Name
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<br />
Country
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
C#
protected void btnInsert_Click(object sender, EventArgs e)
{
DataAccess da = new DataAccess();
int scopeId = da.InsertCustomer(txtName.Text.Trim(), txtCountry.Text.Trim());
lblMessage.Text = "Record inserted successfully. ID = " + scopeId;
}
Screenshot