Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# SQL Visual-Studio
how to write code for inserting new values in different tables....in 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 += ")";
 
 try
 {
 connection.Open();
 adapter.InsertCommand = new SqlCommand(insrtQry, connection);
 adapter.InsertCommand.ExecuteNonQuery();
 
 MessageBox.Show("Row inserted !! ");
 }
 catch (Exception ex)
 {
 MessageBox.Show(ex.ToString());
 }
 }
 }
 
 private void insert_Click(object sender, EventArgs e)
 {
 InsertInfo();
 }
 
 private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
 {
 lstNewRows.Add(e.Row.Index);
 }
Posted 24-Mar-13 22:13pm
Edited 24-Mar-13 22:50pm
Maciej Los158.6K
v2

1 solution

Rate this: bad
good
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).
  Permalink  
Comments
mayuri koul at 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
0 OriginalGriff 365
1 Sergey Alexandrovich Kryukov 329
2 BillWoodruff 210
3 Afzaal Ahmad Zeeshan 204
4 CPallini 185
0 OriginalGriff 5,515
1 DamithSL 4,451
2 Maciej Los 3,902
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,175


Advertise | Privacy | Mobile
Web03 | 2.8.141216.1 | Last Updated 25 Mar 2013
Copyright © CodeProject, 1999-2014
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