The ConnectionString property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
Source Error:
Code
Line 43: cmd.Parameters.AddWithValue("@StudentName",txtName.Text);
Line 44: cmd.Parameters.AddWithValue("@Age",Convert.ToInt32(txtAge.Text));
Line 45: con.Open();
Line 46: int rows = cmd.ExecuteNonQuery();
Line 47: con.Close();
Source File: C:\Users\ajayb\source\repos\WebApplicationpract7c\WebApplicationpract7c\InsertDelete.aspx.cs Line: 45


Amit MohantyRank #112 · 20K reputationPosted Oct 3, 2025, 2:09 AM EDT
Try this once:
int age; if (!int.TryParse(txtAge.Text, out age)) { // Handle invalid input (show message, default to 0, etc.) Response.Write("Please enter a valid number for age."); return; } string connStr = "your-connection-string"; using (SqlConnection con = new SqlConnection(connStr)) { SqlCommand cmd = new SqlCommand( "INSERT INTO students (StudentName, Age) VALUES (@StudentName, @Age)", con); cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age; cmd.Parameters.Add("@StudentName", SqlDbType.NVarChar, 100).Value = txtName.Text; con.Open(); int rows = cmd.ExecuteNonQuery(); }Tuhin PaulRank #7 · 71.9K reputationPosted Oct 3, 2025, 10:48 PM EDT
In your
Web.configfile (at the root of your project), add asection inside:In your
InsertDelete.aspx.csfile, do not hardcode or leave the connection empty. Instead, retrieve it fromWeb.config:using System.Configuration; // Add this at the top // Inside your method (e.g., button click handler) string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand("INSERT INTO Students (StudentName, Age) VALUES (@StudentName, @Age)", con)) { cmd.Parameters.AddWithValue("@StudentName", txtName.Text); cmd.Parameters.AddWithValue("@Age", Convert.ToInt32(txtAge.Text)); con.Open(); int rows = cmd.ExecuteNonQuery(); // con.Close() is automatic due to 'using' block } }Security & Best Practices
.csfiles.usingblocks to auto-dispose connections and commands.txtAge.Textis a number)