Here, I will explain how to insert data into master and detail table in C# using single store procedure.

Generally people create a separate store procedure for each table like master and detail table.
But say you execute a store procedure from C# code for master table (salemaster) and it executes successfully, and again you execute store procedure from C# code for the second table (saledetail) table, but what if the second execution fails for any reason like data mistmatch, run time error occured, sql server connection timeout etc.?
Your master table(salemaster) executed successfully but detail table (saledetail) did not. So there is a problem of relationship because your master table has rows (data) but detail table does not. So how to control this? That's why I am demonstrating this solution for said problem.

First, you need to create a sample database with the two tables, Salemaster and Saledetail, with the following fields and store procedure:

SaleMaster
  1. Create Table SaleMaster
  2. (ID Int NOT NULL identity,
  3. SaleDate Datetime,
  4. CustomerName varchar (50)
  5. )
SaleDetail
  1. Create Table SaleDetail
  2. (ID Int NOT NULL identity,
  3. SalesMasterID Int NOT NULL,
  4. ProdName varchar (50),
  5. Qty decimal (14,2),
  6. Rate decimal (14,2)
  7. )
  8. Create Procedure ADD_SALE_MASTER_DETAIL_TABLE
  9. @SaleDate date,
  10. @Customername varchar (50),
  11. @StrProduct TEXT,
  12. @StrQty TEXT,
  13. @StrRate TEXT,
  14. @Gridcount smallint
  15. AS
  16. Declare
  17. @Product varchar (50),
  18. @Qty decimal(14,2),
  19. @Rate decimal(14,2),
  20. @C1 int,
  21. @C2 int,
  22. @C3 int,
  23. @COUNT INT,
  24. @MAXSRNO INT
  25. SET NOCOUNT ON;
  26. BEGIN TRAN
  27. SET @MAXSRNO=(SELECT ISNULL(MAX(ID),0)+1 FROM SaleMaster)
  28. Insert into SaleMaster(Saledate,customerName)
  29. Values(@Saledate,@Customername)
  30. -------------------Prdouct grid-------------------
  31. SET @C1 = 1
  32. SET @C2 = 1
  33. SET @C3 = 1
  34. SET @COUNT=1
  35. While @Count<=@Gridcount
  36. Begin
  37. SET @Product=CONVERT(CHAR(50),SUBSTRING(@StrProduct ,@C1,20))
  38. SET @Qty =Convert(DECIMAL(14,2),Substring(@StrQty,@C2,14))
  39. SET @Rate =Convert(DECIMAL(14,2),Substring(@StrRate,@C3,14))
  40. Insert Into SaleDetail(SalesMasterID,ProdName,Qty,Rate)
  41. Values(@MaxSrNo,@Product,@Qty,@Rate)
  42. SET @Count=@Count+1
  43. SET @C1=@C1+20
  44. SET @C2=@C2+14
  45. SET @C3=@C3+14
  46. End
  47. -------------------End grid-------------------
  48. COMMIT TRAN
  49. RETURN 0
Now, create the simple Windows Application in Visual Studio.

OUTPUT

Set the controls name as follows:

  1. Datetimepicker
  2. txtCustomer
  3. txtProduct
  4. txtQty
  5. txtRate
  6. dataGridView
  7. btnAdd
Source code
  1. private void btnAdd_Click(object sender, EventArgs e)
  2. {
  3. int add = dataGridView.Rows.Add();
  4. dataGridView.Rows[add].Cells["Product"].Value = txtProduct.Text;
  5. dataGridView.Rows[add].Cells["Qty"].Value = txtQuantity.Text;
  6. dataGridView.Rows[add].Cells["Rate"].Value = txtRate.Text;
  7. txtProduct.Text = "";
  8. txtQuantity.Text = "";
  9. txtRate.Text = "";
  10. if (MessageBox.Show("Add more details", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question)==DialogResult.Yes )
  11. {
  12. txtProduct.Focus ();
  13. }
  14. else
  15. btnSaveData.Focus ();
  16. }
  17. private void btnSaveData_Click(object sender, EventArgs e)
  18. {
  19. //product grid
  20. string product = "";
  21. string qty = "";
  22. string rate = "";
  23. int prodcount = 0;
  24. for (int i = 0; i <= dataGridView.Rows.Count - 1; i++)
  25. {
  26. product = product + Convert.ToString(dataGridView.Rows[i].Cells["Product"].Value).PadRight(20);
  27. qty = qty + Convert.ToString(dataGridView.Rows[i].Cells["Qty"].Value).PadRight(14);
  28. rate = rate + Convert.ToString(dataGridView.Rows[i].Cells["Rate"].Value).PadRight(14);
  29. prodcount += 1;
  30. }
  31. SaveData(dateTimePicker.Value, txtCustomer.Text, product, qty, rate, prodcount);
  32. }
  33. private void SaveData(DateTime _saledate, string _customer, string _product, string _qty, string _rate, int _productcount)
  34. {
  35. var connection = new SqlConnection("data source=(local); initial catalog=SampleData; integrated security=SSPI");
  36. var command = new SqlCommand("ADD_SALE_MASTER_DETAIL_TABLE", connection);
  37. command.Parameters .Add (new SqlParameter("@Saledate",_saledate ));
  38. command.Parameters .Add (new SqlParameter("@customername",_customer ));
  39. command.Parameters .Add (new SqlParameter("@StrProduct",_product ));
  40. command.Parameters .Add (new SqlParameter("@StrQty",_qty));
  41. command.Parameters .Add (new SqlParameter("@StrRate",_rate));
  42. command.Parameters.Add(new SqlParameter ("@Gridcount",_productcount));
  43. command.CommandType = CommandType.StoredProcedure;
  44. connection.Open ();
  45. try
  46. {
  47. int result = command.ExecuteNonQuery();
  48. if (Convert.ToBoolean (result))
  49. {
  50. MessageBox.Show("Record has been successfully saved..");
  51. }
  52. }
  53. catch (Exception ex)
  54. {
  55. MessageBox.Show (ex.Message ,"Message",MessageBoxButtons.OK,MessageBoxIcon.Error );
  56. }
  57. finally
  58. {
  59. connection.Close ();
  60. }
  61. }