Sometimes there is a need to insert bulk records into a database from a Web Form. Suppose there is the requirement of a retail store to add multiple products into a product catalog and then insert these multiple products into the database.
So let's start creating an application so beginners can also understand.
First create the table named ProductsSold using the following script.
CREATE TABLE [dbo].[ProdcutsSold] (
[ProductId] [int] IDENTITY(1,1) NOT NULL,
NULL,
NULL,
[Warrenty] [int] NULL,
[Price] [numeric](18, 2) NULL,
CONSTRAINT [PK_ProdcutsSold] PRIMARY KEY CLUSTERED (
[ProductId] ASC
) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY];
Then the design view of the table will look as follows.

- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
- Provide the website a name such as "InsertbulkRecordsIntoDataBase" or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
- Drag and drop one GridView, two buttons, and four text boxes onto the <form> section of the Default.aspx page.
Now the default.aspx Page source code will look as follows.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="background-color: #0000FF">
<form id="form1" runat="server">
<table style="color:White;">
<tr>
<td>Product Name</td>
<td>Brand Name</td>
<td>Warranty</td>
<td>Price</td>
</tr>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
<asp:Button ID="AddProduct" runat="server" style="color:White" Text="Add Product"
onclick="AddProduct_Click" BackColor="#999966" />
</td>
</tr>
</table>
<div style="margin-top:20px;margin-left:10px;">
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField HeaderStyle-Width="120px" HeaderText="Product Name" DataField="ProductName" />
<asp:BoundField HeaderStyle-Width="120px" HeaderText="Brand Name" DataField="BrandName" />
<asp:BoundField HeaderStyle-Width="120px" HeaderText="Warranty" DataField="Warranty" />
<asp:BoundField HeaderStyle-Width="120px" HeaderText="Price" DataField="Price" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</div>
<div style="margin-top:10px;margin-left:350px">
<asp:Button ID="btnsubmitProducts" runat="server" style="color:White"
Text="Save Products" BackColor="#999966" onclick="btnsubmitProducts_Click" />
</div>
</form>
</body>
</html>
Now switch to design mode and it will look as follows.

Now switch to the default.aspx.cs code behind the file and write the following code to create and save the data table into viewstate and bind the GridView as.
private void AddDefaultFirstRecord()
{
// Creating DataTable
DataTable dt = new DataTable();
DataRow dr;
dt.TableName = "ProductsSold";
// Creating columns for DataTable
dt.Columns.Add(new DataColumn("ProductName", typeof(string)));
dt.Columns.Add(new DataColumn("BrandName", typeof(string)));
dt.Columns.Add(new DataColumn("Warrenty", typeof(int)));
dt.Columns.Add(new DataColumn("Price", typeof(double)));
dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["ProductsSold"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
Now call the function above at Page Load so that the initial records will be added into the view state and Grid View as.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDefaultFirstRecord();
}
}
Now create a function with the following code that will save the records into the data table using view state and will be available to be bound to the Grid View as.
private void AddNewRecordRowToGrid()
{
if (ViewState["ProductsSold"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["ProductsSold"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
// Creating new row and assigning values
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["ProductName"] = TextBox1.Text;
drCurrentRow["BrandName"] = TextBox2.Text;
drCurrentRow["Warrenty"] = Convert.ToInt32(TextBox3.Text);
drCurrentRow["Price"] = Convert.ToDouble(TextBox4.Text);
}
// Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
// Added New Record to the DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
// Storing DataTable to ViewState
ViewState["ProductsSold"] = dtCurrentTable;
// Binding GridView with New Row
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
}
Call the preceding function from the Add Product button and click as.
protected void AddProduct_Click(object sender, EventArgs e)
{
AddNewRecordRowToGrid();
}
Add the database connection string details to the web. config file as.
<connectionStrings>
<add name="dbconn"
connectionString="Data Source=VITHAL;Initial Catalog=C#corner;User Id=sa;word=swift"
providerName="System.Data.SqlClient" />
</connectionStrings>
Now create a function for the connection as.
public void connection()
{
// Storing connection string
constr = ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString;
con = new SqlConnection(constr);
con.Open();
}
Now create the function to save the bulk records into the database using SqlBulkCopy as.
private void BulkInsertToDataBase()
{
DataTable dtProductSold = (DataTable)ViewState["ProductsSold"];
connection();
// Creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(con);
// Assigning destination table name
objbulk.DestinationTableName = "ProdcutsSold";
// Mapping table columns
objbulk.ColumnMappings.Add("ProductName", "ProductName");
objbulk.ColumnMappings.Add("BrandName", "BrandName");
objbulk.ColumnMappings.Add("Warrenty", "Warrenty");
objbulk.ColumnMappings.Add("Price", "Price");
// Inserting bulk records into database
objbulk.WriteToServer(dtProductSold);
}
Call the preceding function on the save product button and click as.
protected void btnsubmitProducts_Click(object sender, EventArgs e)
{
BulkInsertToDataBase();
}
Now the entire code of the default.aspx.cs file will look as follows.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
public string constr;
public SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDefaultFirstRecord();
}
}
public void connection()
{
// Storing connection string
constr = ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString;
con = new SqlConnection(constr);
con.Open();
}
protected void AddProduct_Click(object sender, EventArgs e)
{
AddNewRecordRowToGrid();
}
private void AddDefaultFirstRecord()
{
// Creating DataTable
DataTable dt = new DataTable();
DataRow dr;
dt.TableName = "ProductsSold";
// Creating columns for DataTable
dt.Columns.Add(new DataColumn("ProductName", typeof(string)));
dt.Columns.Add(new DataColumn("BrandName", typeof(string)));
dt.Columns.Add(new DataColumn("Warrenty", typeof(int)));
dt.Columns.Add(new DataColumn("Price", typeof(double)));
dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["ProductsSold"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
private void AddNewRecordRowToGrid()
{
if (ViewState["ProductsSold"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["ProductsSold"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
// Creating new row and assigning values
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["ProductName"] = TextBox1.Text;
drCurrentRow["BrandName"] = TextBox2.Text;
drCurrentRow["Warrenty"] = Convert.ToInt32(TextBox3.Text);
drCurrentRow["Price"] = Convert.ToDouble(TextBox4.Text);
}
// Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
// Adding new record to the DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
// Storing DataTable to ViewState
ViewState["ProductsSold"] = dtCurrentTable;
// Binding GridView with new row
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
}
protected void btnsubmitProducts_Click(object sender, EventArgs e)
{
BulkInsertToDataBase();
}
private void BulkInsertToDataBase()
{
DataTable dtProductSold = (DataTable)ViewState["ProductsSold"];
connection();
// Creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(con);
// Assigning Destination table name
objbulk.DestinationTableName = "ProdcutsSold";
// Mapping Table column
objbulk.ColumnMappings.Add("ProductName", "ProductName");
objbulk.ColumnMappings.Add("BrandName", "BrandName");
objbulk.ColumnMappings.Add("Warrenty", "Warrenty");
objbulk.ColumnMappings.Add("Price", "Price");
// Inserting bulk records into Database
objbulk.WriteToServer(dtProductSold);
}
}
Now run the application. The page will look as follows.

Now add some details into the preceding textboxes and click on the Add Product button. The records that are saved into the DataTable will then be displayed in the GridView as.

Now add another Product detail, it will be added to the existing one.

As in the preceding, you can add n number of records as the data table capacity, now click on the save Products Details button and the records will be saved into the database as follows.

Note
- For detailed code please download the sample Zip file.
- Do proper validation such as date input values when implementing.
- Make the changes in the web. config file depending on your server details for the connection string
Summary
From all the above examples we have learned how to save Bulk Records into a database. I hope this article is useful for all readers, if you have a suggestion then please contact me.

Marwa YoussefPosted Mar 21, 2021, 9:45 PM
Why i have this error while everything is ok and the column name is right. " {"The given ColumnName 'Name' does not match up with any column in data source."} "
Ganga MPosted Apr 18, 2019, 12:30 AM
How to insert same record multiple time without using for loop
Sourav ParamanikPosted Jul 29, 2018, 5:20 AM
The example is great. But I need to do one thing. I want to DELETE a row in the grid GridView1 when I am adding rows in function AddNewRecordRowToGrid() . How to delete it on that time
ejaz mirzaPosted Feb 20, 2018, 12:47 AM
I have paging concept in the grid i can update page only not all the grid values
Sylvia TxyPosted Jan 4, 2018, 7:08 AM
Hi, is there a way to input duplicate product id(primary key) values?
Rana HarisPosted Dec 10, 2017, 2:06 PM
I was using your example to insert bulk data in DB. I added 800 Records in grid view and my computer got powered off/ Restarted due to some light fluctuation. is there any way to Get those 800 Records that have been added in Gridview not in Database?
Hamid KhanPosted Sep 15, 2017, 6:47 AM
How to bulk insert data in multiple tables at a time................
Hamid KhanPosted Sep 7, 2017, 4:50 AM
Very nice article........
Pauline ChanPosted Jan 31, 2016, 10:40 PM
My gridview dies not show in the web page. I didn't change anything from your codes. And also, the data table from where it is getting the data has records already
Vithal WadjePosted Sep 18, 2015, 5:18 PM
share me code
Raj TrivediPosted Sep 17, 2015, 2:16 PM
I am trying the same thing but i am stuck at a place where i have also another table where detail of customer and grandtotal of all the products are stored and i am confused how to simultaneously insert the data in master table and detail with generating Invoice no after inserting the record successfully in both table. One more thing the invoice no should be same for the detail transaction and master transaction.
Vithal WadjePosted Jan 24, 2015, 9:58 AM
sure wait for next
karthi keyanPosted Jan 23, 2015, 8:02 PM
how to clear datatable sir and also i want to know about bulk update into datatable as bulk binsert explained below
Vithal WadjePosted Jan 13, 2015, 1:08 PM
can you explain your question
karthi keyanPosted Jan 13, 2015, 7:29 AM
Default.aspx file
Vithal WadjePosted Jan 4, 2015, 2:25 AM
no such a clear method for Rows
karthi keyanPosted Jan 3, 2015, 2:47 PM
when i use gridview1.Rows.Clear() it is showing an error System.Web.UI.WebControls.GridViewRowCollection' does not contain a definition for 'Clear' and no extension method 'Clear' accepting a first argument of type 'System.Web.UI.WebControls.GridViewRowCollection' could be found (are you missing a using directive or an assembly reference?)
karthi keyanPosted Dec 17, 2014, 3:56 AM
it is updating sir but copy of same product name is updating newly i want to update in time field of existing productname
Vithal WadjePosted Dec 16, 2014, 9:50 PM
set the datetime.now function to variable from whcih you are inserting or updating records
karthi keyanPosted Dec 16, 2014, 8:50 PM
current date to already existing product name record sir
Vithal WadjePosted Dec 16, 2014, 10:23 AM
you wants to update current date or any other
karthi keyanPosted Dec 16, 2014, 8:27 AM
i fetched data from existing table and saved into another table its working fine as you referred and another question sir i want to update current date and time to same table. For eg if i type product name means automatically the product detail is fetching in the details i have to update current date and time help me sir
Vithal WadjePosted Dec 11, 2014, 11:09 AM
yes you can do it also,refer my article list and find autocomplete extender,it will help you
karthi keyanPosted Dec 11, 2014, 10:08 AM
Its working fine sir i made mistake in sql code and another one question sir i want to use only one textbox productname if i type productname means automatically the product detail has to fetch from another table in the database and has to fill in brandnamd, warranty, price in the gridview after clicking on saveproducts the data has to save in database table and also i need to clear the gridview data after clicking save products button
Vithal WadjePosted Dec 10, 2014, 10:50 AM
can you post your code
karthi keyanPosted Dec 10, 2014, 8:02 AM
database table cannot able to access is coming please i need help