Hi leandro.tende...,
Please refer below sample.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
<table>
<tr>
<td>Name:</td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
</tr>
<tr>
<td>Country:</td>
<td><asp:TextBox ID="txtCountry" runat="server" /></td>
</tr>
</table>
<asp:Button Text="Submit" OnClick="Submit" runat="server" />
Namespaces
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Code
protected void Submit(object sender, EventArgs e)
{
string lastId = BLL.BusinessModel.InsertCustomer(txtName.Text, txtCountry.Text);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + lastId + "');", true);
}
Class
DAL
public static class DataAccessModel
{
public static string conn()
{
return @"Server=.\SQL2019;DataBase=Test;UID=sa;PWD=pass@123";
}
public static string ExecutaSQLScalarString(string sql)
{
using (SqlConnection con = new SqlConnection(conn()))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
string res = Convert.ToString(cmd.ExecuteScalar());
con.Close();
return res;
}
}
}
}
BLL
public static class BusinessModel
{
public static string InsertCustomer(string name, string country)
{
string query = string.Format("INSERT INTO Customers VALUES ('{0}','{1}');SELECT SCOPE_IDENTITY();", name, country);
return DAL.DataAccessModel.ExecutaSQLScalarString(query);
}
}
Screenshot
Output