Click here to Skip to main content
15,443,281 members
Please Sign up or sign in to vote.
1.71/5 (3 votes)
See more:
in one Employee table have 3 fields Id,name and department and Id is primary key. And in another table name is a EmployeeSalary and that has a also 3 fields Id,EmpId and salary and EmpId should be foreign key. whenever i run the program at that time i am getting error "SQLEXCEPTION unhandled by user". And breakpoint is show on the SQLCOMMAND object. And this is the insert query.

What I have tried:

String query = "insert into dbo.Employee(Name, department) values(@Name, @Department)";
SqlCommand cmd = new SqlCommand(query,con);
cmd.Parameters.AddWithValue("@Name", txtname.Text);
cmd.Parameters.AddWithValue("@Department", DropDownList1.Text);
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();

con.Open();
String secondQuery = "insert into dbo.EmployeeSalary(Salary) values(@Salary)";
SqlCommand secondCmd = new SqlCommand(secondQuery,con);
secondCmd.Parameters.AddWithValue("@Salary", txtsalary.Text);
secondCmd.CommandText = secondQuery;
secondCmd.Connection = con;
secondCmd.ExecuteNonQuery();
con.Close();
Posted
Updated 27-Jan-18 17:00pm
Comments
phil.o 27-Jan-18 19:00pm    
Wild guess: your Salary column is a number type and you try to assign it a string value. But, not knowing which line throws the exception, and not having the exception message, it is quite hard to find the issue. Please be more precise about the error message you get.

1 solution

There are not enough details. I'm guessing Id from the first table is the Employee Id, the second table is expecting Employee Id (empId) during the Insert. But the code only provide salary. The first query should Insert and return the Id using ExecuteScalar method and the second query should use the Id as EmpId.

Here is a sample code on how to get the last insert Id.
Return Last ID (IDENTITY) On Insert row VB.NET MySQL - Stack Overflow[^]
 
Share this answer
 

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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