0

I am trying to retrieve the ID of the last row inserted in the table.

The insert statement works fine, but I am getting -1 as a return value in the textbox. The SQL code returns the right value when run in SQL Server.

Thanks

// C# code
protected void btnNewPatient_Click(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
    {
        con.Open();

        // SQL statement to insert data in the database
        using(SqlCommand sc = new SqlCommand(@"insert into Patient (HospitalNumber, NHSNumber, DOB, Title, Surname, Forename, Gender, Source) 
                                               values(@HospitalNumber, @NHSNumber, @DOB, @Title, @Surname, @Forename, @Gender, @Source);", con))

        {
            DateTime date = DateTime.ParseExact(txtDob.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            int o = sc.ExecuteNonQuery();
        }

        // SQL statement to retrieve the ID
        using (SqlCommand st = new SqlCommand(@"SELECT IDENT_CURRENT('Patient');", con))
        {
            int o = st.ExecuteNonQuery();
            TextBox1.Text = o.ToString();
        }

        con.Close();              
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Eric Mbiada
  • 133
  • 1
  • 11

0 Answers0