using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; using System.Web.Configuration; public partial class Lec7_Intro_ADONet_DataEntryForm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void submitButton_Click(object sender, EventArgs e) { SqlConnection connection; SqlCommand command; int numRowsAdded; string theName; string theAge; string theCourse; // Read the information posted to this page from the form theName = nameTextBox.Text; theAge = ageTextBox.Text; theCourse = courseTextBox.Text; try { // Connect to the database using the connection string in the web.config file connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString); // Create an INSERT Sql statement // To prevent an Sql injection attack, we add parameters with names starting with an @ symbol command = new SqlCommand("INSERT INTO Student(Name,Age,Course) VALUES(@Name, @Age, @Course)", connection); // Replace the parameters with the actual values read from the form command.Parameters.AddWithValue("@Name", theName); command.Parameters.AddWithValue("@Age", theAge); command.Parameters.AddWithValue("@Course", theCourse); using (connection) { // Open the connection connection.Open(); // Insert the record by executing the command numRowsAdded = command.ExecuteNonQuery(); // Use @@IDENTITY to work out the primary key of // the new row and display it //command.CommandText = "SELECT @@IDENTITY"; //id = Convert.ToInt32(command.ExecuteScalar()); statusLabel.Text = "Record successfully added to database"; // Close the connection connection.Close(); } } catch(Exception exception) { statusLabel.Text = "ERROR: record not added. " + exception.Message; } } }