I have DataGridView
in windows Form using C#.
The data is showing successfully and update also being done successfully.
But the problem is with insertion. When I try to insert multiple data into database using Iteration then the it stores 13 times into database because the datagrid initially show 13 records from database. I meant that it stores new rows multiple times(datagridview rows count) into database.
Lets suppose I want to save two rows into databse but it stores 1st row into database 13 times(total number of datagridview rows).
Please check where I am doing mistake
Note: I want to use single datagridview for displaying, update, insert and delete data from database. I have button through which I want to start insertion all new rows to database.
My code is below
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
using (SqlConnection sqlconn = new SqlConnection(connection))
{
sqlconn.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow)
{
using (SqlCommand sqlcomm = sqlconn.CreateCommand())
{
//sqlcomm.CommandText = "Insert into QF (profileID, UserNameLogInName, UserFullName,Email, forumtitle, subtitle, subjecttitle ,noreply, noview , qtags ,Question ,Questiondetails ,questionstatus, qdate, Status ,todate) values(@status)";
sqlcomm.CommandText = "Insert into QF (UserNameLogInName,Status ) values(@UserNameLogInName,@status)";
try
{
sqlcomm.Parameters.AddWithValue("UserNameLogInName", dataGridView1.CurrentRow.Cells["UserNameLogInName"].Value.ToString());
sqlcomm.Parameters.AddWithValue("Status", dataGridView1.CurrentRow.Cells["Status"].Value.ToString());
sqlcomm.ExecuteNonQuery();
//MessageBox.Show(dataGridView1.Rows[Convert.ToInt32(RecordIndexNumber.Text)].Cells[Convert.ToInt32(ColInexNum.Text)].Value.ToString());
}
catch (Exception ex)
{
btnInsert.Text = ex.Message.ToString();
}
}
}
}
}
I have tried it if (!row.IsNewRow)
and it stores only one row. Without it stores multiple unwanted times into database.
I also used for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
, but the same issue either it stores one or multiple times.
I just wanted to insert the new rows generated by the user on button click.
Try this:
sqlcomm.Parameters.AddWithValue("UserNameLogInName", row.Cells["UserNameLogInName"].Value.ToString());
sqlcomm.Parameters.AddWithValue("Status", row.Cells["Status"].Value.ToString());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.