Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I have wrote this code

SqlConnection con = new SqlConnection("Data Source=MOSTAFA;Initial Catalog=mohasba;Integrated Security=True");

SqlCommand com = new SqlCommand("insert into Ezn_Qaid (Qaid_no,Qaid_date,Maden,Dayn,El_Qema,Qaid_Type,Bayan_Oll) values('" + B_No.Text + "','" + B_Date.Text + "','" + B_m.Text + "','" + B_D.Text + "','" + B_Q.Text + "','" + comboBox3.SelectedIndex + "','" +comboBox1.SelectedIndex+ "')", con);
            
con.Open();
com.ExecuteNonQuery();


and get the following erorr

SQL
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Ezn_Qaid__Bayan___44FF419A". The conflict occurred in database "mohasba", table "dbo.Bayan", column 'byan_name'.
The statement has been terminated.


Note
the database
create table Ezn_Qaid 
( 
Qaid_no nvarchar(20) , 
Qaid_date nvarchar(10)  , 
Maden float , 
Dayn float, 
El_Qema float,
Qaid_Type nvarchar(15) , 
--byan_name int NOT NULL,   -- this is the new column 
Bayan_Oll nvarchar(100) FOREIGN KEY (Bayan_Oll) REFERENCES Bayan(byan_name ),
Bayan_Bank nvarchar(100) FOREIGN KEY (Bayan_Bank ) REFERENCES Bank(byan_name ),
Bayan_3momya nvarchar(100) FOREIGN KEY (Bayan_3momya) REFERENCES msaref_3momya(byan_name ),
Bayan_Tkalef nvarchar(100) FOREIGN KEY (Bayan_Tkalef) REFERENCES tkalef_nshat (byan_name )
) 

create table Bayan
(
byan_no int identity ,
byan_name nvarchar(100)PRIMARY KEY
)

The column byan_name contain only one record "Visa" and the combobox item contain "Visa"

Thanks
Posted

It seems that your command string should not be using comboBox1.SelectedIndex, but should probably use comboBox1.SelectedItem instead. SelectedIndex will give you a 0 out and not the string from the text in the combobox.
 
Share this answer
 
Comments
Dave Kreskowiak 14-Mar-12 17:02pm    
Give that man 5 points!
On top of what Steve said, you might want to Google for ".net parameterized queries" and find out why that pile of string concatentations your using to build the SQL INSERT statement is considered terrible code.
 
Share this answer
 
Comments
Steve Maier 14-Mar-12 17:10pm    
Great addition to the answer. You are definately right about that.
In addition to the other fine answers, your insert statement does not include the byan_name column which means that you are trying to insert a null value to a column that is constrained not to contain a null value.

Remove the constraint or add a value for the column.
 
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