When you asked this last time:
How to calculate months to start date and display in end date[
^]
I told you not to pass strings, but to convert them to appropriate values:
int months;
if (!int.Parse(txtNoOfMonths.Text, out months))
{
return;
}
DateTime startDate;
if (!DateTime.Parse(txtStartDate.Text, out startDate))
{
return;
}
And use the converted values instead of string values to pass directly to SQL.
So do it!
And while you are at it, change your INSERT command:
SqlCommand cmd = new SqlCommand("INSERT INTO monthcal (Startdate, EndDate) VALUES (@StartDate,@EndDate)", con);
cmd.Parameters.AddWithValue("@StartDate", startDate);
cmd.Parameters.AddWithValue("@EndDate", endDate);
con.Open();
cmd.ExecuteNonQuery();
Because if you don't list the columns, it will try to insert the values starting in column order - so SQL will try to put your first parameter into the IDENTITY field, which will never work and will always throw an exception.
And please, do try to Dispose SqlConnection and SqlCommand objects - a
using
block is the easiest way...