using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Web.Configuration; using System.Text; // Encoding namespace BasicAjaxCSharp { public partial class PostFormRead : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnection connection; SqlCommand command; int result; int id; string theName; int theAge; string theCourse; // Set the content type Response.ContentType = "text/plain"; Response.ContentEncoding = Encoding.UTF8; // Read the information posted to this page from the form theName = Request.Form["studentname"]; theAge = int.Parse(Request.Form["studentage"]); theCourse = Request.Form["studentcourse"]; try { connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString); command = new SqlCommand("INSERT INTO Student(Name,Age,Course) VALUES(@Name, @Age, @Course)", connection); command.Parameters.AddWithValue("@Name", theName); command.Parameters.AddWithValue("@Age", theAge); command.Parameters.AddWithValue("@Course", theCourse); using (connection) { connection.Open(); result = command.ExecuteNonQuery(); if (result > 0) { command.CommandText = "SELECT @@IDENTITY"; id = Convert.ToInt32(command.ExecuteScalar()); // Don't cast with (int) Response.Write("Student added, ID is " + id); } else { Response.Write("No record added"); } connection.Close(); } } catch { Response.Write("Error. Student not added"); } } } }