删除所选记录,但不删除当前记录。 c#

问题描述:

private void button4_Click(object sender, EventArgs e) 
{ 
    myConn.Open(); 
    string query = "Delete * from tbl_attendance where [attendance_id] =" + textBox1.Text + ""; 
    OleDbCommand cmd = new OleDbCommand();      
    string message = "Are you sure you want to delete this data?"; 
    string caption = "Delete"; 
    var result = MessageBox.Show(message, caption, MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); 
    if (result == DialogResult.OK) 
    { 
     cmd.Connection = myConn; 
     cmd.CommandText = query; 
     cmd.ExecuteNonQuery(); 
     MessageBox.Show("Successfully deleted recorded data"); 
     button4.Visible = false; 
     button2.Visible = true; 
     label5.Visible = false; 
     textBox1.Visible = false; 
     textBox1.Text = ""; 

     myConn.Close(); 

     try 
     { 
      myConn.Open(); 
      OleDbCommand cmd2 = new OleDbCommand(); 
      cmd2.Connection = myConn; 
      string query2 = "Select attendance_id as [ID], username as [Username], time_in as [Time In],time_out as [Time Out] from tbl_attendance"; 
      cmd.CommandText = query2; 

      OleDbDataAdapter da = new OleDbDataAdapter(cmd); 
      DataTable dt = new DataTable(); 
      da.Fill(dt); 
      dataGridView1.DataSource = dt; 

      myConn.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error " + ex); 
     } 
     myConn.Close(); 
    } 
    else 
    { 
     this.DialogResult = DialogResult.Cancel; 
     button4.Visible = false; 
     button2.Visible = true; 
     label5.Visible = false; 
     textBox1.Visible = false; 
     textBox1.Text = ""; 
    } 
    myConn.Close(); 
} 

我不确定在哪里插入语句,最后插入的数据可能不会被删除。就像,我的datagridview中的任何选定记录都可以删​​除,但不是当前记录,因为它是记录中的最新时间。请帮助。谢谢。删除所选记录,但不删除当前记录。 c#

+0

你为什么要打开和关闭连接这么多? – juharr 2015-03-13 12:53:29

+0

仍然确保一切都运行良好,编程新手。抱歉。 – Niden 2015-03-13 12:57:51

+0

@juharr是对的,我建议你打开cmd.CommandText = query后的连接。然后最后使用该子句并在那里使用myConn.Close(); – Veelicus 2015-03-13 12:58:55

注意事项:

没有你的数据库我不能测试这个

你的代码是不是结构良好的,我不会试图纠正你使用的上网本

。 BAD

我只是打算写的选择等不完整的代码

1:选择该行,您要删除

string id = textBox1.Text; 
deleterow = "Select * from tbl_attendance where id=" + id; 

2:获得最大时间为上删除用户排

maxtime = "select max(timein) from tbl_attendance where username='" + deleterow["username"] + "'"; 

3:获取用户和最大时间行(或列)在

lastrows = "select * from tbl_attendance where username='" +  deleterow["username" + "' and timein='" + maxtimein + "'"; 

4:比较与一个最后的行ID你tryign删除

if (lastrows["id] == id) 
{ 
//dont delete! 
} 
+0

明白了,谢谢 – Niden 2015-03-13 13:29:16