Click here to Skip to main content
11,929,675 members (48,617 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# SQL Visual-Studio
how to write code for inserting new values in different multiple rows

i hv used the following code to insert new values in one new row of different tables dat i select from combo box-

connectionString = @"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
 connection = new SqlConnection(connectionString);
 foreach (int rowIndex in lstNewRows)
 string insrtQry = "insert into " + comboBox1.Text + " values(";
 foreach (DataGridViewCell cell in dataGridView1.Rows[rowIndex].Cells)
 insrtQry += "'" + cell.Value.ToString() + "',";
 insrtQry = insrtQry.TrimEnd(",".ToCharArray());
 insrtQry += ")";
 adapter.InsertCommand = new SqlCommand(insrtQry, connection);
 MessageBox.Show("Row inserted !! ");
 catch (Exception ex)
 private void insert_Click(object sender, EventArgs e)
 private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
Posted 24-Mar-13 22:13pm
Edited 24-Mar-13 22:50pm
Maciej Los210.1K

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Look for Transaction: that allows for several queries to be executed as a block. If one of the queries fails, you can do a Rollback to get to the previous state of your database.
By the way, it is advisable to use parameterized queries: they help prevent SQL injection attacks, and they help dealing with odd datatypes (e.g. datetime values or strings with quotation marks).
mayuri koul 25-Mar-13 5:21am
well sir,thnks for your answer but can you help me by giving a sample code

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.151126.1 | Last Updated 25 Mar 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100