girmachew gulint

girmachew gulint

  • NA
  • 85
  • 1.6k

Insert data to sql server from Textbox which is in a loop

Nov 6 2019 12:44 PM
Getting data from SQL Table
  1. using (var con = new SqlConnection(constr))  
  2. {  
  3. string query = "select * from higher_office";  
  4. using (var cmd = new SqlCommand(query, con))  
  5. {  
  6. using (var sda = new SqlDataAdapter())  
  7. {  
  8. cmd.Connection = con;  
  9. sda.SelectCommand = cmd;  
  10. using (TableData)  
  11. {  
  12. TableData.Clear();  
  13. sda.Fill(TableData);  
  14. }  
  15. }  
  16. }  
  17. }  
aspx fetched data and new Textbox for inputing values corresponding to higher office
  1. <% for (var data = 0; data < TableData.Rows.Count; data++)  
  2. {  
  3. %>  
  4. <tr>  
  5. <td>  
  6. <%=TableData.Rows[data]["higher_office_ID"]%>  
  7. </td>  
  8. <td>  
  9. <%=TableData.Rows[data]["higher_office_Name"]%>  
  10. </td>  
  11. <td>  
  12. <asp:TextBox ID="TextBox1" runat="server" width="150px" ></asp:TextBox>  
  13. </td>  
  14. </tr>  
  15. <% } %>  
trying to insert as follows but not excute
  1. using (SqlConnection con = new SqlConnection(constr))  
  2. {  
  3. con.Open();  
  4. //SqlCommand cm = new SqlCommand("insert into item_distribution (sector,quantity) values('" + id + "','" + amount+ "')", con);  
  5. for (int i = 1; i <= rowCount; i++)  
  6. {  
  7. SqlCommand cm = new SqlCommand("insert into item_distribution (sector,quantity) values('"+ id +"','"+ amount+"')",con);  
  8. try  
  9. {  
  10. cm.ExecuteNonQuery();  
  11. RoleMessage.Text += "Successfully inserted";  
  12. RoleMessageDIV.Style["display"] = "block";  
  13. }  
  14. catch(Exception ex )  
  15. {  
  16. RoleMessage.Text +="Not inserted "+ex;  
  17. RoleMessageDIV.Style["display"] = "block";  
  18. }  
  19. }  
  20. con.Close();  
  21. }  

Answers (1)