Saturday, August 10, 2019

How to insert bulk data (multiple rows) to a SQL Server database using ASP.NET

I explain how to insert bulk data (multiple rows) to a SQL Server database using ASP.NET.
One of the common problems I have seen is to bulk data insert to a SQL Server database at a time using ASP.Net Application. Here in this post I have done this easily following these simple steps.

Here I have created a page containing a Gridview with no of blank rows(on demand) for take inputs in application end, and created a stored procedure with a parameter (xml type) for accept bulk data at a time in sql server end.


Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table for Save Records.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used table as below

Step-4: Create a Stored Procedure for Save bulk data.

Right Click on Stored Procedure (in your database) > Add new Stoted procedure > Write following SQL Code And Execute.


  1. CREATE PROCEDURE [dbo].[ContactBulkInsert]
  2. @XMLData xml
  3. AS
  4. Create table #tempContact(
  5. FirstName varchar(50) not null,
  6. LastName varchar(50) not null,
  7. ContactNo varchar(50) not null
  8. );
  9.  
  10. Insert into Contacts(FirstName,LastName,ContactNo)
  11. Select
  12. contact.query('FirstName').value('.', 'varchar(50)') as FirstName,
  13. contact.query('LastName').value('.', 'varchar(50)') as LastName,
  14. contact.query('ContactNo').value('.', 'varchar(50)') as ContactNo
  15. FROM
  16. @XMLData.nodes('/contacts/contact')AS xmlData(contact)
  17. RETURN

Step-5: Add a Webpage and Design for Save/Show Multiple Records to/from SQL Server Database.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code 
  1. <h3>Insert Multiple Record in a SQL Database using ASP.Net application.</h3>
  2. <div style="padding:10px 0px">
  3. No of record you want to insert :
  4. <asp:TextBox ID="txtNoOfRecord" runat="server"></asp:TextBox>
  5. &nbsp;
  6. <asp:Button ID="btnAddRow" runat="server" Text="Add Rows" OnClick="btnAddRow_Click" />
  7.  
  8. </div>
  9. <asp:GridView ID="gvContacts" runat="server" AutoGenerateColumns="false" CellPadding="5">
  10. <Columns>
  11. <asp:TemplateField HeaderText="SL No.">
  12. <ItemTemplate>
  13. <%#Container.DataItemIndex +1 %>
  14. </ItemTemplate>
  15. </asp:TemplateField>
  16. <asp:TemplateField HeaderText="First Name">
  17. <ItemTemplate>
  18. <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
  19. </ItemTemplate>
  20. </asp:TemplateField>
  21. <asp:TemplateField HeaderText="Last Name">
  22. <ItemTemplate>
  23. <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
  24. </ItemTemplate>
  25. </asp:TemplateField>
  26. <asp:TemplateField HeaderText="Contact No">
  27. <ItemTemplate>
  28. <asp:TextBox ID="txtContactNo" runat="server"></asp:TextBox>
  29. </ItemTemplate>
  30. </asp:TemplateField>
  31. </Columns>
  32. </asp:GridView>
  33. <div style="padding:10px 0px;">
  34. <asp:Panel ID="Panel1" runat="server" Visible="false">
  35. <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
  36. &nbsp;<asp:Label ID="lblMsg" runat="server" ></asp:Label>
  37. </asp:Panel>
  38. </div>
  39. <div>
  40. <b>Database Records</b>
  41. <div>
  42. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="5">
  43. <Columns>
  44. <asp:TemplateField HeaderText="SL No.">
  45. <ItemTemplate>
  46. <%#Eval("ID") %>
  47. </ItemTemplate>
  48. </asp:TemplateField>
  49. <asp:TemplateField HeaderText="First Name">
  50. <ItemTemplate>
  51. <%#Eval("FirstName") %>
  52. </ItemTemplate>
  53. </asp:TemplateField>
  54. <asp:TemplateField HeaderText="Last Name">
  55. <ItemTemplate>
  56. <%#Eval("LastName") %>
  57. </ItemTemplate>
  58. </asp:TemplateField>
  59. <asp:TemplateField HeaderText="Contact No">
  60. <ItemTemplate>
  61. <%#Eval("ContactNo") %>
  62. </ItemTemplate>
  63. </asp:TemplateField>
  64. </Columns>
  65. </asp:GridView>
  66. </div>
  67. </div>

Step-6: Write code in page_load event for fetch and show existing data from database.


  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. PopulateData();
  6. }
  7. }
and here is the function
  1. private void PopulateData()
  2. {
  3. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
  4. {
  5. SqlCommand cmd = new SqlCommand("Select * from Contacts", con);
  6. if (con.State != System.Data.ConnectionState.Open)
  7. {
  8. con.Open();
  9. }
  10. DataTable dt = new DataTable();
  11. dt.Load(cmd.ExecuteReader());
  12. GridView1.DataSource = dt;
  13. GridView1.DataBind();
  14. }
  15. }

Step-7: Write code in button (btnAddRow) click event for add blank row in gridview for take inputs.


  1. protected void btnAddRow_Click(object sender, EventArgs e)
  2. {
  3. AddRowsToGrid();
  4. }
and here is the function
  1. private void AddRowsToGrid()
  2. {
  3. List<int> noofRows = new List<int>();
  4. int rows = 0;
  5. int.TryParse(txtNoOfRecord.Text.Trim(), out rows);
  6.  
  7. for (int i = 0; i < rows; i++)
  8. {
  9. noofRows.Add(i);
  10. }
  11.  
  12. gvContacts.DataSource = noofRows;
  13. gvContacts.DataBind();
  14. if (gvContacts.Rows.Count > 0)
  15. {
  16. Panel1.Visible = true;
  17. }
  18. else
  19. {
  20. Panel1.Visible = false;
  21. }
  22. }

Step-8: Write code in button (btnSave) click event for Save multiple records to SQL Server database.


  1. protected void btnSave_Click(object sender, EventArgs e)
  2. {
  3. // Save Here
  4. StringBuilder sb = new StringBuilder();
  5. sb.AppendLine("<?xml version=\"1.0\" ?>");
  6. sb.AppendLine(" <contacts>");
  7.  
  8. // Check Validity
  9. TextBox txtFirstName;
  10. TextBox txtLastName;
  11. TextBox txtContactNo;
  12.  
  13. foreach (GridViewRow row in gvContacts.Rows)
  14. {
  15. txtFirstName = (TextBox)row.FindControl("txtFirstName");
  16. txtLastName = (TextBox)row.FindControl("txtLastName");
  17. txtContactNo = (TextBox)row.FindControl("txtContactNo");
  18.  
  19. if (txtFirstName == null || txtLastName == null || txtContactNo == null)
  20. {
  21. return;
  22. }
  23.  
  24. if (string.IsNullOrEmpty(txtFirstName.Text.Trim())
  25. || string.IsNullOrEmpty(txtLastName.Text.Trim())
  26. || string.IsNullOrEmpty(txtContactNo.Text.Trim()))
  27. {
  28. lblMsg.Text = "All fields are required!";
  29. return;
  30. }
  31. else
  32. {
  33. sb.AppendLine(" <contact>");
  34. sb.AppendLine(" <FirstName>" + txtFirstName.Text.Trim() +"</FirstName>");
  35. sb.AppendLine(" <LastName>" + txtLastName.Text.Trim() + "</LastName>");
  36. sb.AppendLine(" <ContactNo>" + txtContactNo.Text.Trim() + "</ContactNo>");
  37. sb.AppendLine(" </contact>");
  38. }
  39.  
  40. }
  41. sb.AppendLine(" </contacts>");
  42.  
  43. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
  44. {
  45. SqlCommand cmd = new SqlCommand("ContactBulkInsert", con);
  46. cmd.CommandType = CommandType.StoredProcedure;
  47. cmd.Parameters.AddWithValue("@XMLData", sb.ToString());
  48. if (con.State != ConnectionState.Open)
  49. {
  50. con.Open();
  51. }
  52.  
  53. int affRow = cmd.ExecuteNonQuery();
  54. if (affRow > 0)
  55. {
  56. lblMsg.Text = "Successfully " + affRow + " record inserted.";
  57. PopulateData();
  58. AddRowsToGrid();
  59. }
  60. }
  61. }
Step-9: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...