anna john

anna john

  • NA
  • 47
  • 8.1k

pls help on datagrid view insert /update operation

Oct 4 2019 3:58 PM
Hi all,
 
i have a table employee;[MSACESS database] it has an ID which is auto generated.
in datagrid view, the id field is hidden. name and department values user should enter.
so for current row , if there is no ID value, then it should be insert.
else , if there is an id value is present it should be update. my code below not looking into that.
can you please help me
  1. private void DgvWizard_CellValueChanged(object sender, DataGridViewCellEventArgs e)  
  2. //insert or update into database the values from the datagridview  
  3. if (dgvWizard.CurrentRow != null)  
  4. {  
  5. using (OleDbConnection Connection = new OleDbConnection(connectionString))  
  6. {  
  7. Connection.Open();  
  8. DataGridViewRow dgvRow = dgvWizard.CurrentRow;  
  9. try  
  10. {  
  11. if(dgvRow.Cells["txtEmpID"].Value==DBNull.Value)  
  12. cmd = new OleDbCommand(cmdText: "insert into employees(name,contact) values (@name,@contact)", Connection);  
  13. //if employeeid is null, then it should insert the current row  
  14. else  
  15. cmd = new OleDbCommand(cmdText: "update employees set name =@name, contact=@contact where empid=@empid", Connection);  
  16. //if employee id is not null, it means its an existing record and use update query  
  17. cmd.Parameters.AddWithValue("@name", dgvRow.Cells["txtEmployeeName"].Value == DBNull.Value ? "" : dgvRow.Cells["txtEmployeeName "].Value.ToString());  
  18. cmd.Parameters.AddWithValue("@empid ", Convert.ToInt32(dgvRow.Cells["txtEmpID "].Value == DBNull.Value ? "" : dgvRow.Cells["txtEmpID "].Value));  
  19. cmd.Parameters.AddWithValue("@contact", dgvRow.Cells["txtContactName"].Value == DBNull.Value ? "" : dgvRow.Cells["txtContactName"].Value.ToString());  
  20. cmd.ExecuteNonQuery();  
  21. MessageBox.Show("Success!");  
  22. }  
  23. catch (Exception ee) { }  
  24. }  
  25. }  
  26. }  

Answers (2)