2017-08-08 74 views
0

當我點擊時添加數據將轉到子表和上述數據轉到主表。如何從主表中獲取最大ID並基於該表插入主表中的一條記錄和子表中的一條或多條條目

下面是設計的一個截圖:

enter image description here

保存按鈕單擊事件:

protected void btnsave_Click(object sender, EventArgs e) 
    { 
     SqlConnection con2 = new SqlConnection(@"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;[email protected]"); 
     con2.Open(); 
     SqlCommand cd = new SqlCommand("insertmaster", con2); 
     cd.CommandType = CommandType.StoredProcedure; 
     cd.Parameters.AddWithValue("@name", txtname.Text.Trim()); 
     cd.Parameters.AddWithValue("@age", txtage.Text.Trim()); 
     cd.Parameters.AddWithValue("@gender", Radiogender.SelectedItem.ToString()); 
     cd.ExecuteNonQuery(); 
     con2.Close(); 

     foreach (GridViewRow item in gv.Rows) 
     { 


      SqlConnection con = new SqlConnection(@"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;[email protected]"); 
      con.Open(); 
      string statment = string.Format("insert into child_table ([relative_name], [relation]) values ('{0}','{1}')", item.Cells[0].Text, item.Cells[1].Text); 
      SqlCommand cmd = new SqlCommand(statment, con); 
      cmd.CommandType = CommandType.Text; 
      cmd.ExecuteNonQuery(); 
      con.Close(); 

     } 

     successmsg.Text = "Data Inserted Successfully"; 
    } 
+0

您需要提供您迄今爲止所嘗試的內容以及您遇到的問題/問題。 Stackoverflow不是提供現成的代碼/解決方案的平臺! – Rohit

+0

@rohit我編輯過,請看看 – Ashish

+0

你得到了什麼錯誤? – Rohit

回答

0

你必須在你的程序如下編寫SQL查詢,並從應用程序中調用你的程序:

DECLARE @id INT 
    INSERT INTO MainPerson VALUES(Name,Age,Male) 
    SET @id= SCOPE_IDENTITY() 
    INSERT INTO RelativePerson Values(@id,Name,Relation) 

由於您必須使用Sc ope_Identity爲了獲得插入到主表中的最後一個ID。

+0

我已經使用gridview來存儲子表的臨時數據。 – Ashish

+0

你必須使用用戶定義類型的存儲過程作爲它的參數,並將你的子表作爲參數發送到Sp看到以下鏈接:[link](https://www.codeproject.com/Articles/412802/Sending-a -DataTable到存儲過程) –

+0

但我不知道如何在我的項目中實現這一點。 – Ashish

0

改變你的代碼如下:

SqlConnection con2 = new SqlConnection(@"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;[email protected]"); 
con2.Open(); 
SqlCommand cd = new SqlCommand("insertmaster", con2); 
cd.CommandType = CommandType.StoredProcedure; 
cd.Parameters.AddWithValue("@name", txtname.Text.Trim()); 
cd.Parameters.AddWithValue("@age", txtage.Text.Trim()); 
cd.Parameters.AddWithValue("@gender", Radiogender.SelectedItem.ToString()); 
string id = cd.GetScalar(); 
con2.Close(); 

,改變你的insertmaster程序進行:

Insert into MainTable values(name,age,gender) 
Select SCOPE_IDENTITY() 

然後你會得到ID使用,要在子表的代碼中插入。

相關問題