2013-05-29 99 views
1

我已经有一些数据放入网格视图。现在我想插入多行到gridview然后怎么做?从网格视图到数据库的多个数据插入

如果我去了foreach循环,那么它会占用已经存在的所有行的数量并且多次插入数据。相反,我要到新行仅

下面是我的代码

private void userInsert() 
    { 
     if (MessageBox.Show("Do you want to add the new data ?", "Confirm ", MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes) 
     { 
      cmd.Connection = con; 
      cmd.CommandType = CommandType.Text; 
      try 
      { 

       foreach (GridViewRow dRow in userDataGridView.Rows) 
       { 
        cmd.CommandText = string.Format("insert into users(first_name,last_name,default_rate,default_location,spi_user_id,nickname) values('{0}','{1}',{2},{3},{4},'{5}')", userDataGridView.CurrentRow.Cells[0].Value.ToString(), userDataGridView.CurrentRow.Cells[1].Value.ToString(), userDataGridView.CurrentRow.Cells[2].Value.ToString(), locationID2ComboBox.SelectedValue, userDataGridView.CurrentRow.Cells[4].Value.ToString(), userDataGridView.CurrentRow.Cells[5].Value.ToString()); 
        con.Open(); 
        cmd.ExecuteNonQuery(); 
       } 
       MessageBox.Show("Your data has been added successfully ", "Saved info", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
      finally 
      { 
       con.Close(); 
       userSelect(); 
      } 
     } 
    } 
+2

请告诉我们你做了什么至今?你的代码! – 7alhashmi

回答

0

要么保留该行被插入轨道(可以使用Tag财产例如完成,或修改您的SQL查询来检查,如果数据是已经存在

if not exists (select top 1 * from users u where u.first_name = '{0}' and u.last_name = '{1}') 
    insert into users(first_name,last_name,default_rate,default_location,spi_user_id,nickname) 
    values('{0}','{1}',{2},{3},{4},'{5}' 

,你可能需要更多的参数检查的独特性。我还建议您使用参数与SqlCommand

如果你想使用Tag财产(只有当它是Winforms项目!):

foreach (GridViewRow dRow in userDataGridView.Rows) 
{ 
    var check = dRow.Tag as bool? ?? false; //was row already processed? 

    if (check) 
    { 
     continue; 
    } 

    cmd.CommandText = string.Format("insert into users(first_name,last_name,default_rate,default_location,spi_user_id,nickname) values('{0}','{1}',{2},{3},{4},'{5}')", userDataGridView.CurrentRow.Cells[0].Value.ToString(), userDataGridView.CurrentRow.Cells[1].Value.ToString(), userDataGridView.CurrentRow.Cells[2].Value.ToString(), locationID2ComboBox.SelectedValue, userDataGridView.CurrentRow.Cells[4].Value.ToString(), userDataGridView.CurrentRow.Cells[5].Value.ToString()); 
    con.Open(); 
    cmd.ExecuteNonQuery(); 

    dRow.Tag = true; 
} 
0

什么是用户ID和谁产生的呢?

如果用户ID为0,新用户的简单

foreach (GridViewRow dRow in userDataGridView.Rows) 
       { 
        if(userDataGridView.CurrentRow.Cells[<user id index>]==0) 
         { 
         //add into DB 
         } 

       } 

希望这有助于

0

您可以使用此事件中加入新的记录:

private void dataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e) 
{ 
    //e.Row.Cells[0].Value <-- Use 'e.Row' argument to access the new row 
} 
相关问题