Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have two tables, table details are attached here while inserting data into database foreighnkey column shows as null. Please help me.

First table
Hide Copy Code
CREATE TABLE MASTER1 (
ID int (primary key),
EMPNAME varchar(50)
,EMPID varchar(50) ,
DEPARTMENT varchar(50)
,TITLE varchar(50) ,
CATEGORY varchar(50) , OTHERDETAILS varchar(50),)
second table
Hide Copy Code
CREATE TABLE addition(
ID_EMP int (foreighnkey connect with ID of EMPMASTER),
EMP_NAME varchar(50)
EMP_ID varchar(50) ,
EMP_DEPARTMENT varchar(50) )
Stored procedure
Hide Copy Code
CREATE PROCEDURE [dbo].[EmployeeIns]

@EMPNAME VARCHAR(50),@EMPID VARCHAR(50),@DEPARTMENT VARCHAR(50),
@TITLE VARCHAR(500),@CATEGORY VARCHAR(500),@OTHERDETAILS varchar(500)
AS
BEGIN

INSERT INTO MASTER1(EMPNAME,EMPID,DEPARTMENT,TITLE ,CATEGORY,OTHERDETAILS)VALUES(@EMPNAME,@EMPID,@DEPARTMENT,@TITLE,@CATEGORY,@OTHERDETAILS)
END
Hide Expand Copy Code
public void fillgrid()

for (int i = 0; i < GridView1.Rows.Count; i++)

SqlConnection SC = sqlconnection;
SC.Open();
string strEMPNAME = GridView1.Rows[i].Cells[0].Text.ToString().Trim();
string strEMPID = GridView1.Rows[i].Cells[1].Text.ToString().Trim();
string strDEPARTMENT = GridView1.Rows[i].Cells[2].Text.ToString().Trim();
SqlCommand cmd = new SqlCommand("insert into addition (EMP_NAME,EMP_ID,EMP_DEPARTMENT) values('" + strEMPNAME + "','" + strEMPID + "','" + strDEPARTMENT + "' )", SC);
cmd.ExecuteNonQuery();
SC.Close();

protected void Button1_Click(object sender, EventArgs e)

SC.Open();
SqlCommand cmd = new SqlCommand("EmployeeIns", SC);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@EMPNAME", txtname.Text);
cmd.Parameters.AddWithValue("@EMPID", txteid.Text);
cmd.Parameters.AddWithValue("@DEPARTMENT", drpdept.SelectedValue);
cmd.Parameters.AddWithValue("@TITLE", Txttitle.Text);
cmd.Parameters.AddWithValue("@CATEGORY", drpcatgry.SelectedValue);
cmd.Parameters.AddWithValue("@OTHERDETAILS", txtothers.Text);
cmd.ExecuteNonQuery();
fillgrid();
sc.close();
Posted

1 solution

You have to insert data in the foreign key column yourself, the system will not do this for you.

Generally you :
1) insert data into the master table and get the row ID for the insert.
2) insert data into the details withe the above ID as the foreign key.
 
Share this answer
 
Comments
Unni R 8-May-15 0:44am    
I am new in Asp and sql can you please give one solution
Mehdi Gholam 8-May-15 0:52am    
Google : c# crud tutorial

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