First off, appending the values from your input to your SQL statement is a big NO NO, as it can lead you to SQL injection attack. Read:
Protect Your Data: Prevent SQL Injection[^][
^]
Second, make it a habit to put objects that eat resources such as
SqlConnection
within a
using statement
to ensure that objects will be properly disposed and closed after they are used.
Third, don't write your code for calculating the age at
TextChanged
event because that event will always be triggered when you type/change something from the
TextBox
. As an alternative, you could instead write the code at
Button
's
Click
event.
Now down your issue...
You said,
Age
column is of type integer. Now looking at your code at
TextChanged
event, you are using this:
txtAge.Text = years.ToString() + "/" + months.ToString();
Now your txtAge.Text value contains the character "/" which triggers the error you have. An integer type can only accept numeric values so you need to ensure that the value of your TxtAge should only contain numeric values. To prevent that, you could:
1. implement client-side validation to allow only numeric values for your txtAge using JavaScript/jQuery
2. as suggested, use
Int32.TryParse Method (System)[
^] to re-validate the value at the server. For example:
int age;
if(Int32.TryParse(txtAge.Text.Trim(), out age))
{
}
else
{
Response.Write("Not valid");
}