2015-03-13 256 views
0
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

回答

0

注意事項:

沒有你的數據庫我不能測試這個

你的代碼是不是結構良好的,我不會試圖糾正你使用的上網本

。 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