In this blog we will know how to insert data from Gridview to database.

Scenario - Records will be displayed in the gridview from an xml file. Then when we click insert button all data present in the gridview will be inserted to the database.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Insert_data_from_Gridview_database._Default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" >
  4. <head runat="server">
  5. <title>Untitled Page</title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
  11. <asp:GridView ID="GridView1" runat="server">
  12. </asp:GridView>
  13. <asp:Button ID="btn_insert" runat="server" onclick="btn_insert_Click"
  14. Text="Insert Records" />
  15. <asp:Button ID="btn_show" runat="server" onclick="btn_show_Click"
  16. style="height: 26px" Text="Show Records" />
  17. </div>
  18. </form>
  19. </body>
  20. </html>
  1. using System;
  2. using System.Collections;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Security;
  8. using System.Web.UI;
  9. using System.Web.UI.HtmlControls;
  10. using System.Web.UI.WebControls;
  11. using System.Web.UI.WebControls.WebParts;
  12. using System.Xml.Linq;
  13. using System.Data.SqlClient;
  14. namespace Insert_data_from_Gridview_database
  15. {
  16. public partial class _Default : System.Web.UI.Page
  17. {
  18. string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
  19. SqlCommand com;
  20. protected void btn_show_Click(object sender, EventArgs e)
  21. {
  22. DataSet reportData = new DataSet();
  23. reportData.ReadXml(Server.MapPath("student.xml"));
  24. GridView1.DataSource = reportData;
  25. GridView1.DataBind();
  26. }
  27. protected void btn_insert_Click(object sender, EventArgs e)
  28. {
  29. foreach (GridViewRow g1 in GridView1.Rows)
  30. {
  31. SqlConnection con = new SqlConnection(connStr);
  32. com = new SqlCommand("insert into student(sid,sname,smarks,saddress) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
  33. con.Open();
  34. com.ExecuteNonQuery();
  35. con.Close();
  36. }
  37. Label1.Text = "Records inserted successfully";
  38. }
  39. }
  40. }
Thanks for reading.