Skip to content
Loading
Insert Multiple rows in gridview.
.cs page
  1. protected void Bulk_Insert(object sender, EventArgs e)  
  2. {  
  3.     DataTable dt = new DataTable();  
  4.     dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"typeof(int)),  
  5.                 new DataColumn("Name"typeof(string)),  
  6.                 new DataColumn("Company",typeof(string)) });  
  7.     foreach (GridViewRow row in gv.Rows)  
  8.     {                  
  9.         if (row.RowType == DataControlRowType.DataRow)  
  10.         {  
  11.             RadioButtonList rbl_responses = (RadioButtonList)row.Cells[2].FindControl("RadioButtonList1");  
  12.             if (rbl_responses.SelectedIndex >= 0)  
  13.             {  
  14.                 dt.Rows.Add(int.Parse(row.Cells[0].Text), row.Cells[1].Text, rbl_responses.SelectedValue);  
  15.             }  
  16.         }  
  17.     }  
  18.   
  19.     if (dt.Rows.Count > 0)  
  20.     {  
  21.         string consString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;  
  22.         using (SqlConnection con = new SqlConnection(consString))  
  23.         {  
  24.             using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))  
  25.             {  
  26.                 //Set the database table name  
  27.                 sqlBulkCopy.DestinationTableName = "dbo.tblNewCustomers";  
  28.                 sqlBulkCopy.ColumnMappings.Add("Id""CustomerId");  
  29.                 sqlBulkCopy.ColumnMappings.Add("Name""Name");  
  30.                 sqlBulkCopy.ColumnMappings.Add("Company""Company");  
  31.                 con.Open();  
  32.                 sqlBulkCopy.WriteToServer(dt);  
  33.                 con.Close();  
  34.             }  
  35.         }  
  36.     }