Last Reply on Jan 17, 2012 10:22 PM By Mudassar
Posted on Dec 08, 2011 04:38 AM

Hi,

 

    I want to insert multiple rows of data from a gridview to database table in a single button click event.

 

Results 1 - 5 of 7 1 2
Posted on Dec 09, 2011 07:14 AM

You can loop through the rows in GridView and extract each row values to be inserted.

Here's a quick example:

 

protected void Button1_Click(object sender, EventArgs e)
{
 StringCollection sc = new StringCollection();
 string field1 = string.Empty;
 
 for (int i = 0; i < GridView1.Rows.Count; i++)//loop the GridView Rows{

            field1 = GridView1.Rows[i].Cells[0].Text; // get the  field to be Inserted
            sc.Add(field1); // add the field to be Inserted in the StringCollection

 }
 
     InsertRecords(sc); // call method for insert and pass the StringCollection values
     
}


//Multiple Inserts
private void InsertRecords(StringCollection sc)
{
   SqlConnection conn = new SqlConnection("Your Connection String");
   StringBuilder sb = new StringBuilder(string.Empty);
 
   foreach (string item in sc)
   {
     const string sqlStatement = "INSERT INTO TableName (ColumnName) VALUES ";
     sb.AppendFormat("{0}'{1}'; ",sqlStatement, item);
   }
   try
   {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
     }
     finally
     {
            conn.Close();
     }

}

 

Posted on Dec 19, 2011 04:14 AM

Thanks for the code...

I am getting error as "insert error" I am using a columns.

const string sqlStatement = "INSERT INTO TableName (ColumnName) VALUES ";

     sb.AppendFormat("{0}'{1}'; ",sqlStatement, item);
I am not able to get this line of code plz send the code as example of a columns ...
Posted on Dec 19, 2011 06:56 AM
Posted on Dec 20, 2011 02:36 AM

 

What's the actual error you get? can you post it here?

 

SabirJani says:

Thanks for the code...

I am getting error as "insert error" I am using a columns.

const string sqlStatement = "INSERT INTO TableName (ColumnName) VALUES ";

     sb.AppendFormat("{0}'{1}'; ",sqlStatement, item);
I am not able to get this line of code plz send the code as example of a columns ...