Input string was not in a correct format.
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.FormatException: Input string was not in a correct format.
Source Error:
Line 42: SqlCommand cmd = new SqlCommand("insert into students(StudentName,Age) values(@StudentName,@Age)",con);
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();
Source File: C:\Users\ajayb\source\repos\WebApplicationpract7c\WebApplicationpract7c\InsertDelete.aspx.cs Line: 44

Tuhin PaulPosted Oct 4, 2025, 2:50 AM
The error "Input string was not in a correct format" occurs on Line 44 because
txtAge.Textcontains a value that cannot be converted to an integer usingConvert.ToInt32().This happens when:
Cynthia SathuragiriPosted Oct 8, 2025, 5:32 AM
Convert.ToInt32(txtAge.Text)
failed because txtAge.Text is not a valid number.
int age;
if (!int.TryParse(txtAge.Text, out age))
{
// Handle invalid input
lblMessage.Text = "Please enter a valid number for age.";
return;
}
SqlCommand cmd = new SqlCommand("INSERT INTO students (StudentName, Age) VALUES (@StudentName, @Age)", con);
cmd.Parameters.AddWithValue("@StudentName", txtName.Text);
cmd.Parameters.AddWithValue("@Age", age);
con.Open();
int rows = cmd.ExecuteNonQuery();
con.Close();
lblMessage.Text = "Record inserted successfully!";
Sandhiya PriyaPosted Oct 6, 2025, 4:45 AM
Let’s break it down clearly
Error Message
Line 44:
Root Cause
This error means:
Common causes:
txtAge.Textis empty (e.g.,"")txtAge.Textcontains non-numeric characters (like"twenty","12 years","12.5", or" "spaces)The textbox value is null
The page is not validating input before inserting
Fix: Validate Before Converting
You must ensure the input is numeric before calling
Convert.ToInt32().Safe Fix:
What
int.TryParse()DoesIt tries to convert text to integer.
If it fails, it does not throw an exception.
It returns
false— letting you show a user-friendly message instead.Bonus Tip — Input Validation
To prevent invalid input from the start, you can add an ASP.NET validator in your
.aspxpage:Summary
int.TryParse()Amit MohantyPosted Oct 3, 2025, 6:05 AM
The errror is triggered on this line: cmd.Parameters.AddWithValue("@Age", Convert.ToInt32(txtAge.Text));
That means txtAge.Text is not a valid integer at runtime.
This can occur if:
So, before using, you should validate the input:
But my recommendations is don’t use AddWithValue blindly. It can cause type mismatches. Use SqlDbType: