Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello i want to insert the gridview row in database. here gridview row can be multiple at a single time. i have done this using loop but loop can hit database as row present in the gridview so can you tell me any method with that i can insert multiple record in a single time.

What I have tried:

i have use loop like this
C#
if (gvSample!= null)
           {
               for (int i = 0; i < (gvSample.Rows.Count; i++)
               {
                   GridViewRow row = this.(gvSample.Rows[i];
                   SqlCommand cmd = new SqlCommand();
                   cmd.CommandType = CommandType.StoredProcedure;
                   cmd.CommandText = "sp_Insert";
                   cmd.Parameters.AddWithValue("@Id", txtNumber.Text);
                   cmd.Parameters.AddWithValue("@Name", gvSample.Rows[i].Cells[1].Text);
                   cmd.Parameters.AddWithValue("@Document", gvSample.Rows[i].Cells[2].Text);
                  cmd.ExecuteNonQuery();
               }
           }
Posted
Updated 12-Dec-16 20:37pm
v3
Comments
ZurdoDev 12-Dec-16 7:10am    
What's wrong with the code you have?
AZHAR SAYYAD 13-Dec-16 1:29am    
there is not any issue in this code. i want to send only one time. here in this code because of loop this code hitting the server multiple time. i want to hit only single time and insert the multiple record by passing the multiple record in single method.

1 solution

You can insert multiple row by creating Type of Table in Sql and pass the DataTable to Procedure
SQL
CREATE TYPE _table AS TABLE
(
Id INT,
Name VARCHAR(100),
DOCUMENT VARCHAR(200)
)

Alter You Procedure
SQL
ALTER PROC sp_Insert
(
   @tablevariable _table READONLY
)
AS
BEGIN
   INSERT INTO YourTable(Id,Name,Document) SELECT Id,Name,Document FROM @tablevariable
END


Code Change
C#
if (gvSample!= null)
           {
		DataTable _dt = new DataTable();
_dt.Columns.Add("Id");
_dt.Columns.Add("Name");
_dt.Columns.Add("Document");
               for (int i = 0; i < gvSample.Rows.Count; i++)
               {
                   GridViewRow row = this.(gvSample.Rows[i]);
_dt.Rows.Add(gvSample.Rows[i].Cells[0].Text,gvSample.Rows[i].Cells[1].Text, gvSample.Rows[i].Cells[2].Text);
               }
SqlCommand cmd = new SqlCommand();
                   cmd.CommandType = CommandType.StoredProcedure;
                   cmd.CommandText = "sp_Insert";
                   cmd.Parameters.AddWithValue("@tablevariable", _dt );
                  cmd.ExecuteNonQuery();
           }
refrence:

[Insert Bulk Row at a time]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900