Save values between 'Steps' in Wizard ASP.NET - c#

I get this error in ASP.NET Wizard when I try to use values of TextBox control of previous step.
Error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contact_Emp".
The conflict occurred in database "KKSTech", table "dbo.Emp", column 'EmpID'.
Is it a problem to access control's values of different steps?

This is the First class that inserts into dbo.Emp table
public void InsertInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String insertstring = #"insert into Emp (EmpID, FirstName, LastName, MiddleName, Mob1, Mob2, Phone, Email1, Email2, EmpDesc)
values (#EmpID, #FirstName, #LastName, #MiddleName, #Mob1, #Mob2)";
SqlCommand cmd = new SqlCommand(insertstring, conn);
cmd.CommandText = insertstring;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.Parameters.AddWithValue("#FirstName", TextBox2.Text);
cmd.Parameters.AddWithValue("#LastName", TextBox3.Text);
cmd.Parameters.AddWithValue("#MiddleName", TextBox4.Text);
cmd.Parameters.AddWithValue("#Mob1", TextBox5.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox6.Text);
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
And this is the one where I 'm inserting into the table where EmpID is a FK
public void Insertaddress()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String str = #"insert into Contact (Addressline1, Addressline2, CityID, EmpID)
values(#Addressline1, #Addressline2, #CityID, #EmpID)";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.CommandText = str;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#Addressline1", TextBox15.Text);
cmd.Parameters.AddWithValue("#Addressline2", TextBox17.Text);
cmd.Parameters.AddWithValue("#CityID", DropDownList2.SelectedValue);
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
That was my problem.

A foreign key ensures that it cannot have a value in that column that is not also in the primary key column of the referenced table.
In your case , you are inserting EmpID into contact table which is not present in the referenced table of EmpID i.e Emp table.

Related

How to insert into specific columns of a database

The problem is am getting an exception error that says data mismatch in the external database when i try to insert
I have a customer booking table with booking id ...pk as auto number, customer.... fk and date in as datetime
Booking id is auto increment so i don't need to insert anything
What i want to achieve is to insert into customer_id and date in thats all but i keep getting the data mismatch and number of query valuesis not the same as destination fields
So what is the right way to put this
using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking ([customer_id],[date_in]) values (?,?)";
cmd.Parameters.AddWithValue("#customer_id", txtusername.Text);
cmd.Parameters.AddWithValue("#date_in", dtdate_in);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
use cmd.Parameters.add('...') method as follow :
using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking ([customer_id],[date_in]) values (#customer_id,#date_in)";
///* Set your column dataType*/
cmd.Parameters.Add("#customer_id", SqlDbType.VarChar , 50).Value = txtusername.Text;
cmd.Parameters.Add("#date_in", SqlDbType.DateTime).Value = dtdate_in;
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}

How to use last insert id pass to another table

How to use last insert id pass to another table
i have two table 1.product 2.stock i have enclosed with images below.
stack table proid is last insert id come from product table which should add on stock table but
i couldn't add please see the code i tried below
MySqlCommand cm1 = new MySqlCommand();
cm1.Connection = con;
cm1.CommandText = "insert into products(name,qty,price) values (#name,#qty,#price)";
cm1.Parameters.AddWithValue("#name", textBox1.Text);
cm1.Parameters.AddWithValue("#qty", textBox3.Text);
cm1.Parameters.AddWithValue("#price", textBox4.Text);
con.Open();
// Return the id of the new record. Convert from Int64 to Int32 (int).
// return Convert.ToInt32(cm1.Parameters["#newId"].Value);
MySqlCommand cm = new MySqlCommand();
cm.Connection = con;
cm.CommandText = "insert into stock(caname,qty,price) values (#caname,#qty,#price)";
//cm.CommandText = "insert into products(name,qty,price) values (#caname,#qty,#price)";
// cm.Parameters.AddWithValue("#name", textBox1.Text);
// cm.Parameters.AddWithValue("#proid", id);
cm.Parameters.AddWithValue("#caname", textBox2.Text);
cm.Parameters.AddWithValue("#qty", textBox3.Text);
cm.Parameters.AddWithValue("#price", textBox4.Text);
cm.ExecuteNonQuery();
cm1.ExecuteNonQuery();

data is not getting saved

using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-O72COGQ;Initial Catalog=ClinicManagementtest;Integrated Security=True"))
{
con.Open();
SqlCommand sc = new SqlCommand("INSERT INTO Patient_Details VALUES(#Id, #Name, #Age, #Contact No, #Address", con);
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
sc.Parameters.AddWithValue("#Contact No", textBox3.Text);
sc.Parameters.AddWithValue("#Address", textBox5.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
con.Close();
}
You are making a lot of errors here.
First, you have 6 fields in your table and, if you don't give a list
of fields when you make an insert query, then you should add values
for all 6 fields.
Second you have 5 parameters placeholders but you add only 4
parameters and this is another exception.
Last but not least the syntax of the insert statement is formally
wrong because there is no closing parenthesys
So, let's try to fix at the best of our knowledge
string cmdText = #"INSERT INTO Patient_Details
(ID, Name, Age, Gender, [Contact No], Address)
VALUES(#Id,#Name,#Age,#Gender,#ContactNo, #Address)"
using (SqlConnection con = new SqlConnection(....))
{
con.Open();
SqlCommand sc = new SqlCommand(cmdText, con);
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
// For the following two fields, add a value or remove
// the parameters and fix the query text above....
sc.Parameters.AddWithValue("#age", ????);
sc.Parameters.AddWithValue("#gender", ????);
sc.Parameters.AddWithValue("#ContactNo", textBox3.Text);
sc.Parameters.AddWithValue("#Address", textBox5.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
}
Like Sankar Raj pointed out you missed the a ) in the Insert query and a parameter #Age to add.Using space in parameter #Contact No is also not allowed.
You have used using for SqlConnection.I suggest you use the same for SqlCommand also, then you don't need to explicitly Dispose it. And again it seems you are not using try catch that's you were not able to identity the problem.
SUGGESTED CODE
try{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-O72COGQ;Initial Catalog=ClinicManagementtest;Integrated Security=True"))
{
con.Open();
using (SqlCommand sc = new SqlCommand("INSERT INTO Patient_Details VALUES(#Id, #Name, #Age,#Gender, #ContactNo, #Address)", con)){
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
sc.Parameters.AddWithValue("#Gender", textBox3.Text);
sc.Parameters.AddWithValue("#ContactNo", textBox4.Text);
sc.Parameters.AddWithValue("#Age", textBox5.Text);
sc.Parameters.AddWithValue("#Address", textBox6.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
}
}
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
Note: I've removed con.Close(). Since you are using using statement it will automatically Close & Dispose the Connection and release the resources it uses.

I need to update my database values using c#. But there is an error message when running. What can be the reason?

I have four text box values called txtName, txtId, txtAdd, txtTel. I need to update an existing record in my database table. But the code is not working. Can someone help me to identify my errors. Here is my code.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\User\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database4.mdf;Integrated Security=True");
try
{
String name = txtName.Text;
String id = txtId.Text;
String address = txtAdd.Text;
String tel = txtTel.Text;
String SqlQuery = "UPDATE [Table]VALUES (#id,#name,#tel,#address)";
SqlCommand cmnd = new SqlCommand(SqlQuery, con);
con.Open();
cmnd.ExecuteNonQuery();
MessageBox.Show("Saved Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error occured while saving" + ex);
}
finally
{
con.Close();
}
Plese help me
Your update Syntax is wrong. Also add the parameters to your command:
SQL UPDATE Syntax:
UPDATE table_name SET column1=value1,column2=value2,...
WHERE some_column=some_value;
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\User\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database4.mdf;Integrated Security=True");
try
{
String name = txtName.Text;
String id = txtId.Text;
String address = txtAdd.Text;
String tel = txtTel.Text;
String SqlQuery = "UPDATE [Table] SET name = #name, tel = #tel, [address] = #address where [id] = #id";
SqlCommand cmnd = new SqlCommand(SqlQuery, con);
cmnd.Parameters.AddWithValue("#id", id);
cmnd.Parameters.AddWithValue("#name", name);
cmnd.Parameters.AddWithValue("#tel", tel);
cmnd.Parameters.AddWithValue("#address", address);
con.Open();
cmnd.ExecuteNonQuery();
MessageBox.Show("Saved Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error occured while saving" + ex);
}
finally
{
con.Close();
}
Your update query is wrong. Please see some examples.
After assigning your TextBox values to some strings, make sure that you use them after that.
You don't need to write (in your case) finally{} block manually, use using() statement instead of that.
Put your SqlCommand into using().
Use parameterized queries
Try this:
try
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\User\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database4.mdf;Integrated Security=True"))
{
con.Open();
using(SqlCommand cmnd = con.CreateCommand())
{
// Your update query must look like something like this
cmnd.CommandText = #"UPDATE [Table]
SET Name = #name,
Tel = #tel,
Address = #address
WHERE Id = #id";
cmd.Parameters.Add(new SqlParameter("#id", txtId.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtName.Text));
cmd.Parameters.Add(new SqlParameter("#tel", txtTel.Text));
cmd.Parameters.Add(new SqlParameter("#address", txtAdd.Text));
cmnd.ExecuteNonQuery();
MessageBox.Show("Saved Successfully");
}
}
}
catch(Exception ex)
{
//Handle your exception here
}
I guess you could try adding these lines of code to add parameters:
cmnd.Parameters.Add(new SqlParameter("#id", id);
cmnd.Parameters.Add(new SqlParameter("#name", name);
cmnd.Parameters.Add(new SqlParameter("#tel", tel);
cmnd.Parameters.Add(new SqlParameter("#address", address);

"Error converting data type nvarchar to numeric."

I want to Insert record to the database with a ComboBox. The ComboBox is connected to the other table and this is the error:
Error converting data type nvarchar to numeric.
private void InsertReceipt()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)" +
"VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
cmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
cmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
cmd.Parameters.AddWithValue("#Store", txtStore.Text);
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
cmd.Parameters.AddWithValue("#NoStub", txtStub.Text);
cmd.ExecuteNonQuery();
}
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname + ', ' + lastname AS Name FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "Customer.Name";
cboName.ValueMember = "Customer.CustomerID";
}
When you call AddWithValue make sure that the type of data you are passing matches the column type. Here's a likely candidate:
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
In this line you are passing a text string to something that clearly wants a numeric value (an amount). You should parse the txtAmount.Text into a decimal first and then pass that value:
decimal amount = decimal.Parse(txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", amount);
With this code, you may still get an exception if the string in txtAmount.Text can't be parsed into a decimal, but at least then you'll know which value is causing the problem. You can/should do the same with the other values as well to make sure they match their column types.
try string.isNullorEmpty(txtAmount.text);
private void button1_Click(object sender, EventArgs e)
{
string sql;
sql = "insert into slab (date,sober_visor,tesh,shift,group,heat_no,st_grade,thick,width,length,location,pcs,remarkes,slab_no) values (#date,#sober_vsor,#tesh,#shift,#group,#heat_no,#st_grade,#thick,#width,#length,#loction,#pcs,#slab_no);select scope_identity()";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#date", txt_date.Text);
cmd.Parameters.AddWithValue("#sober_visor", com_sober_visor.ToString());
cmd.Parameters.AddWithValue("#shift", txt_shift.Text);
cmd.Parameters.AddWithValue("#heat_no", txt_heat_no.Text);
cmd.Parameters.AddWithValue("#thick", txt_shift.Text);
cmd.Parameters.AddWithValue("#width", txt_heat_no.Text);
cmd.Parameters.AddWithValue("#length", txt_length.Text);
cmd.Parameters.AddWithValue("#pcs", txt_pcs.Text);
cmd.Parameters.AddWithValue("#st_grade", txt_st_gread.Text);
cmd.Parameters.AddWithValue("#location", txt_loction.Text);
cmd.Parameters.AddWithValue("#slab_no", txt_slab_no.Text);
con.Open();
cmd.ExecuteNonQuery();
txt_heat_no.Text = cmd.ExecuteScalar().ToString();
con.Close();
MessageBox.Show("تمت عملية الإضافة");
}
}
}
cmd.Parameters.AddWithValue("#ödenecektutar", Convert.ToDecimal(tutar1.Text.Substring(0, tutar.Text.Length - 1)));

Categories