Sunday, August 11, 2019

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

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 Update bulk data.

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

  1. CREATE PROCEDURE dbo.ContactBulkUpdate
  2. @XMLData xml
  3. AS
  4. Create table #tempContact
  5. (
  6. ID int not null,
  7. FirstName varchar(50) not null,
  8. LastName varchar(50) not null,
  9. ContactNo varchar(50) not null
  10. )
  11.  
  12. Insert into #tempContact (ID, FirstName, LastName, ContactNo)
  13. Select
  14. contact.query('ID').value('.','int') as ID,
  15. contact.query('FirstName').value('.','varchar(50)') as FirstName,
  16. contact.query('LastName').value('.','varchar(50)') as LastName,
  17. contact.query('ContactNo').value('.','varchar(50)') as ContactNo
  18. From
  19. @XMLData.nodes('/contacts/contact') as xmlData(contact)
  20.  
  21. Update Contacts
  22. Set
  23. FirstName = b.FirstName,
  24. LastName = b.LastName,
  25. ContactNo = b.ContactNo
  26. from
  27. #tempContact as b
  28. Where
  29. Contacts.ID = b.ID
  30. RETURN

Step-5: Add a Webpage and Design for Show/Update Multiple Records from/to 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>Bulk update in ASP.NET</h3>
  2. <div style="padding:20px">
  3.  
  4. <asp:GridView ID="gvContacts" runat="server" AutoGenerateColumns="false" CellPadding="5" DataKeyNames="ID">
  5. <Columns>
  6. <asp:TemplateField HeaderText="ID">
  7. <ItemTemplate>
  8. <asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
  9. </ItemTemplate>
  10. </asp:TemplateField>
  11. <asp:TemplateField HeaderText="First Name">
  12. <ItemTemplate>
  13. <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
  14. </ItemTemplate>
  15. </asp:TemplateField>
  16. <asp:TemplateField HeaderText="Last Name">
  17. <ItemTemplate>
  18. <asp:TextBox ID="txtLastName" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
  19. </ItemTemplate>
  20. </asp:TemplateField>
  21. <asp:TemplateField HeaderText="Contact No">
  22. <ItemTemplate>
  23. <asp:TextBox ID="txtContactNo" runat="server" Text='<%# Bind("ContactNo") %>'></asp:TextBox>
  24. </ItemTemplate>
  25. </asp:TemplateField>
  26. </Columns>
  27. </asp:GridView>
  28. <div style="padding:20px;">
  29. <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
  30. <asp:Label ID="lblMsg" runat="server" ></asp:Label>
  31. </div>
  32. </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. DataTable dt = new DataTable();
  6. SqlCommand cmd = new SqlCommand("Select * from Contacts", con);
  7. if (con.State != ConnectionState.Open)
  8. {
  9. con.Open();
  10. }
  11.  
  12. dt.Load(cmd.ExecuteReader());
  13.  
  14. gvContacts.DataSource = dt;
  15. gvContacts.DataBind();
  16. }
  17. }

Step-7: Write code in button (btnUpdate) click event for Update multiple records to SQL Server database.


  1. protected void btnUpdate_Click(object sender, EventArgs e)
  2. {
  3. StringBuilder sb = new StringBuilder();
  4. sb.AppendLine("<?xml version=\"1.0\" ?>");
  5. sb.AppendLine(" <contacts>");
  6. TextBox txtFirstName;
  7. TextBox txtLastName;
  8. TextBox txtContactNo;
  9. foreach (GridViewRow row in gvContacts.Rows)
  10. {
  11. int ID = Convert.ToInt32(gvContacts.DataKeys[row.RowIndex].Values["ID"].ToString());
  12. txtFirstName = (TextBox)row.FindControl("txtFirstName");
  13. txtLastName = (TextBox)row.FindControl("txtLastName");
  14. txtContactNo = (TextBox)row.FindControl("txtContactNo");
  15.  
  16. if (txtFirstName == null || txtLastName == null || txtContactNo == null)
  17. {
  18. return;
  19. }
  20. if (String.IsNullOrEmpty(txtFirstName.Text.Trim()) || String.IsNullOrEmpty(txtLastName.Text.Trim())||
  21. String.IsNullOrEmpty(txtContactNo.Text.Trim()))
  22. {
  23. lblMsg.Text = "All fields are required!";
  24. return;
  25. }
  26. else
  27. {
  28. sb.AppendLine(" <contact>");
  29. sb.AppendLine(" <ID>" + ID + "</ID>");
  30. sb.AppendLine(" <FirstName>" + txtFirstName.Text.Trim() + "</FirstName>");
  31. sb.AppendLine(" <LastName>" + txtLastName.Text.Trim() + "</LastName>");
  32. sb.AppendLine(" <ContactNo>" + txtContactNo.Text.Trim() + "</ContactNo>");
  33. sb.AppendLine(" </contact>");
  34. }
  35. }
  36. sb.AppendLine(" </contacts>");
  37. //Update query here
  38. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
  39. {
  40. SqlCommand cmd = new SqlCommand("ContactBulkUpdate", con);
  41. cmd.CommandType = CommandType.StoredProcedure;
  42. cmd.Parameters.AddWithValue("@XMLData", sb.ToString());
  43. if (con.State != ConnectionState.Open)
  44. {
  45. con.Open();
  46. }
  47. int aff = cmd.ExecuteNonQuery();
  48. if (aff > 0)
  49. {
  50. lblMsg.Text = "Successfully Updated!";
  51. //pOPULATE Updated data again.
  52. PopulateData();
  53. }
  54. else
  55. {
  56. lblMsg.Text = "Failed! Please try again.";
  57. }
  58. }
  59. }

Step-8: 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 { ...