Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
My table

SQL
create table monthcal
(
Id int primary key identity (1,1),
StartDate date,
EndDate date
)


.cs

C#
SqlCommand cmd = new SqlCommand("Insert into  monthcal values (@NoOfMonths,@StartDate,@EndDate)", con);
        cmd.Parameters.AddWithValue("@NoOfMonths", txtNoOfMonths.Text.ToString());
        cmd.Parameters.AddWithValue("@StartDate", txtStartDate.Text.ToString());
        cmd.Parameters.AddWithValue("@EndDate", txtEndDate.Text.ToString());
        con.Open();
        cmd.ExecuteNonQuery();

    }


am getting an error

An explicit value for the identity column in table 'monthcal' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Posted
Updated 23-May-15 1:09am
v3

1 solution

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:
C#
int months;
if (!int.Parse(txtNoOfMonths.Text, out months))
   {
   // Report problem with number!
   return;
   }
DateTime startDate;
if (!DateTime.Parse(txtStartDate.Text, out startDate))
   {
   // Report problem with Date!
   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:
C#
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...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900