You need a few changes here, like adding error handling. To get the reason behind the exception, you need to check the Errors property of the exception:
try
{
//Your code here
}
catch (SqlCeException e)
{
foreach (SqlCeError error in e.Errors)
{
//Error handling, etc.
MessageBox.Show(error.Message);
}
}
Doing that, it will tell you exactly what the error is.
I think your User_id and Exam_id 'parameters' are being treated as strings in the SQL statement, as you are surrounding it with single quotes. At a guess, this will be your problem along with missing logic operators in the WHERE clause.
However don't do parameterization this way! You leave yourself open to SQL Injection attacks when you concatenate your query this way. There's lots of articles and information on MSDN on how to do this, or take a look at this from Jeff Atwood - http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
Update
Ok, to break it down further, based on the comment by marc_s, you can't use SCOPE_IDENTITY() in SQL CE. So you're looking at doing this:
A parameterized insert:
var sqlString = "Insert into Finalresult(Section_name, userId, examid) Select Section_name, User_id, Exam_id from result " +
"WHERE (User_id = @userId AND Exam_id = @examId AND Section_name = @sectionName"
cmd.CommandText = sqlString;
cmd.Parameters.Add("@userId", userid);
cmd.Parameters.Add("@examId", examId);
cmd.Parameters.Add("@sectionName", section);
cmd.ExecuteNonQuery();
And then on the same connection (but different command of course), get the inserted id:
cmd.Connection = _connection;
cmd.CommandText = "SELECT @@identity";
Int32 newId = (Int32)cmd.ExecuteScalar();
I haven't tested or compiled this, so just take it as an idea/guidance.