Click here to Skip to main content
15,896,493 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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-

C#
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
Updated 24-Mar-13 21:50pm
v2

1 solution

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).
 
Share this answer
 
Comments
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)



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