Online Earning Sources (Without Investment)

If you want to post, send your post on dotnetglobe@gmail.com .Put 'Title' as 'Subject'

Pages

Sunday, July 19, 2009

Bulk Insert into Sql Server Database in Asp.Net using C#

We see bulk insert by taking 1 example :

Create 1 table into Database
For ex., Database Name : Employee
Create Table :- EmpInfo(EmpId,EmpName,Address,City)

After making this goto .aspx.cs page and create 1 datatable in which you can insert data .

Step 1 :

//Create Datatable
void CreateDT()
{
DataTable dt = new DataTable("Emp");
dt.Columns.Add("EmpCode");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Address");
ViewState["dt"] = dt;
}

Step 2 : Create simple form to take employee information from user
step 3: Put add button
Step 4 : Add Grid in Page to display record of DataTable

Step 5 : write below code on btnAdd_Click() event to add form data into DataTable

protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
DataRow dr = dt.NewRow();
dr["EmpCode"]=Convert.ToInt64(TextBox1.Text);
dr["FirstName"] = TextBox2.Text;
dr["LastName"] = TextBox3.Text;
dr["Address"] = TextBox4.Text;
dt.Rows.Add(dr);
ViewState["dt"] = dt;
BindGrid();
}

Step 6 : Put 1 more button to test Bulk Insert

Write the below code in the btnBulkInsert_Click() event to Insert records of DataTable into EmpInfo Table

//'EmployeeConnectionString' is the connection string name which is defined in web.config file
protected void btnBulkInsert_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConnectionString"].ToString());
SqlBulkCopy bulkcopy = new SqlBulkCopy(con1);
bulkcopy.DestinationTableName = "EmpInfo";
con1.Open();
//For Map the DataTable columns with Sql Server Table
//bulkcopy.ColumnMappings.Add(datatable column,Sql server Column)
bulkcopy.ColumnMappings.Add(0, 0);
bulkcopy.ColumnMappings.Add(1, 1);
bulkcopy.ColumnMappings.Add(2, 3);
bulkcopy.ColumnMappings.Add(3, 4);
bulkcopy.WriteToServer((DataTable)ViewState["dt"]);
con1.Close();
}

1 comment:

bhsoft said...

nice article....

itworld