Mohit Kumar

Mohit Kumar

  • NA
  • 11
  • 1.2k

Trying to insert multiple rows data of Dataset in a table.

Mar 7 2019 2:45 PM
I wrote a code to insert multiple rows from dataset into a sql table.
I put insert inside foreach loop scope but it take first row only.
 
Please check the code below
 
  1. string query, feetype, feename, feeamt;  
  2. //Get Fees charges from Fees  
  3. Master
sda = new SqlDataAdapter("select class,fees_type,fess_name, fee_amount from tb_fee_master where class='" + stclass + "' and not fees_type='Monthly'", sc);
  
  4. ds = new DataSet();
  
  5. sda.Fill(ds, "t");
  
  6. if (ds.Tables[0].Rows.Count != 0)  
  7. 
{  
  8. 
stclass = ds.Tables[0].Rows[0][0].ToString();
  
  9. feetype = ds.Tables[0].Rows[0][1].ToString();
  
  10. feename = ds.Tables[0].Rows[0][2].ToString();
  
  11. feeamt = ds.Tables[0].Rows[0][3].ToString();
  
  12. int x = 0;
foreach(DataRow dr in ds.Tables[0].Rows)
  
  13. {  
  14. if (dr.Table.Rows.Count > 0)  
  15. {  
  16. query = "insert into tb_std_fee (class,fee_type,fee_name, amount) values (@class,@fee_type,@fee_name, @amount)";  
  17. cmd = new SqlCommand(query, sc);  
  18. cmd.Parameters.AddWithValue("@class", stclass);  
  19. cmd.Parameters.AddWithValue("@fee_type", feetype);  
  20. cmd.Parameters.AddWithValue("@fee_name", feename);  
  21. cmd.Parameters.AddWithValue("@amount", feeamt);  
  22. sc.Open();  
  23. x = cmd.ExecuteNonQuery();  
  24. sc.Close();  
  25. }  
  26. }  
  27. if (x != 0)  
  28. {  
  29. MessageBox.Show("Fees register created successfully.");  
  30. }  
  31. }

Answers (2)