Israel

Israel

  • 698
  • 1.3k
  • 217.6k

How to make a simple loop until last record

Jan 15 2020 10:56 PM
Hi,
 
I would like to do a Loop with these codes. But I need to explain very well what I try to do.
 
1) On my form I have a Datagrid, one TextBox and a Button
 
2) I have a table name “Test”with a 2 columns (Company_name and Company). This table have 5 records
 
3) After displaying each “Company” its should send all company’s names into one table named “Receive”
 
Let’s see what I do. Its works but without with loop:
 
Company_name             Company
---------------------               ------------
Andrews                         Company1
McSean                          Company2
Nokia                              Company2
TelCell                            Company1
Flex                                Company1
  1. conn.Open();  
  2. SqlCommand cmd1 = conn.CreateCommand();  
  3. cmd1.CommandType = CommandType.Text;  
  4. cmd1.CommandText = "select * from Test where company = @company;  
  5. var param1 = new SqlParameter("@company", SqlDbType.NChar);  
  6. param1.Value = txtBoxCompany.Text;  
  7. {  
  8. cmd1.Parameters.Add(param1);  
  9. cmd1.Parameters.Add(param2);  
  10. }  
  11. cmd1.ExecuteNonQuery();  
  12. DataTable dt1 = new DataTable();  
  13. SqlDataAdapter da1 = new SqlDataAdapter(cmd1);  
  14. da1.Fill(dt1);  
  15. conn.Close();  
  16. dgvTest.DataSource = dt1;  
  17. Then after displaying the result on my datagrid its should send in block names of company on other table “Receive”  
  18. string myConnectionString;  
  19. myConnectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename=C:\\Test\\WindowsFormsApplication1\\App_datas\\Accounting.mdf;Integrated Security = True;Integrated Security = True";  
  20. using (var con = new SqlConnection())  
  21. {  
  22. con.ConnectionString = myConnectionString;  
  23. con.Open();  
  24. using (var cmd = new SqlCommand())  
  25. {  
  26. cmd.Connection = con;  
  27. cmd.CommandType = System.Data.CommandType.Text;  
  28. cmd.CommandText = @"INSERT INTO Test (company_name, company) SELECT company_name, company FROM test where company = @company";  
  29. cmd.Parameters.AddWithValue("@company", txtBox_company.Text);  
  30. cmd.ExecuteNonQuery();  
  31. }  
  32. con.Close();  
  33. }  
  34. Console.WriteLine("Done.");  
But all of these should doing as a loop one by one record until read and transfering the last record. Many thanx.

Answers (2)