Hi sindiyen,
Please refer below sample.
HTML
<table>
Name :
<asp:TextBox ID="txtName" runat="server" />
<br />
Country :
<asp:TextBox ID="txtCountry" runat="server" />
<br />
<asp:Button ID="btnInsert" Text="Insert" runat="server" OnClick="btnInsert_Click" />
</table>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data.SqlClient
Imports System.Data
Code
C#
protected void btnInsert_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Customers (Name,Country) VALUES(@Name,@Country)", con);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Country", txtCountry.Text);
con.Open();
cmd.ExecuteScalar();
con.Close();
cmd = new SqlCommand("SELECT MAX(CustomerID) ID FROM Customers ", con);
con.Open();
int id = Convert.ToInt16(cmd.ExecuteScalar());
con.Close();
cmd = new SqlCommand("INSERT INTO TestDemo1 (CustomerId,Name,Country) VALUES(@CustomerId,@Name,@Country)", con);
cmd.Parameters.AddWithValue("@CustomerId", id);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Country", txtCountry.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
VB.Net
Protected Sub btnInsert_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Dim cmd As SqlCommand = New SqlCommand("INSERT INTO Customers (Name,Country) VALUES(@Name,@Country)", con)
cmd.Parameters.AddWithValue("@Name", txtName.Text)
cmd.Parameters.AddWithValue("@Country", txtCountry.Text)
con.Open()
cmd.ExecuteScalar()
con.Close()
cmd = New SqlCommand("SELECT MAX(CustomerID) ID FROM Customers ", con)
con.Open()
Dim id As Integer = Convert.ToInt16(cmd.ExecuteScalar())
con.Close()
cmd = New SqlCommand("INSERT INTO TestDemo1 (CustomerId,Name,Country) VALUES(@CustomerId,@Name,@Country)", con)
cmd.Parameters.AddWithValue("@CustomerId", id)
cmd.Parameters.AddWithValue("@Name", txtName.Text)
cmd.Parameters.AddWithValue("@Country", txtCountry.Text)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using