Insert Multiple Rows from ASP.NET

Take a WebForm and design by taking the following one.

login

The “Add to datatable” button will add rows to a datatable. On clicking the “Add to database” button, all the rows from the datatable will be inserted in a database table with the help of a stored procedure which takes a Table Valued Parameter.
The table structure is as below:

  1. CREATE TABLE [dbo].[BCP](  
  2.     [Name] [varchar](50) NULL,  
  3.     [Age] [intNULL  
  4. )   
The TVP is as below:
  1. create type tbl1 as table  
  2. (nm varchar(50),ag int)  
The stored procedure is as below:
  1. CREATE PROCEDURE InsertBcp  
  2.   (@tvp1 dbo.tbl1 READONLY)  
  3.   as begin  
  4.   insert bcp   
  5.   select * from @tvp1  
  6.   end    
Code for the Page Load event:
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.     {  
  5.         DataTable dt = new DataTable();  
  6.         dt.Columns.Add("Name"typeof(string));  
  7.         dt.Columns.Add("Age"typeof(int));  
  8.         Session["datatable"] = dt;  
  9.     }  
  10.   
  11. }  
Code for the “Add to datatable” button:
  1. DataTable dt = (DataTable)Session["datatable"];  
  2. dt.Rows.Add(TextBox1.Text, Convert.ToInt32(TextBox2.Text));  
Code for the “Add to database” button:
  1. DataTable dt = (DataTable)Session["datatable"];  
  2. SqlConnection conn =  
  3.   new SqlConnection("server=.;database=cts1;integrated security=true");  
  4. SqlCommand cmd = new SqlCommand("InsertBcp", conn);  
  5. cmd.CommandType = CommandType.StoredProcedure;  
  6. cmd.Parameters.AddWithValue("@tvp1", dt);  
  7. conn.Open();  
  8. cmd.ExecuteNonQuery();  
  9. conn.Close();  
Remember to use session state because of ASP.NET’s stateless nature.

Ebook Download
View all
Learn
View all