Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
private void btnUpdate_Click(object sender, EventArgs e)

                // Get the selected row index.
                int selectedRowIndex = dgvFacultyLeaveList.CurrentRow.Index;

                // Get the Faculty_ID of the selected row.
                string facultyID = txtID.Text.Trim();

                // Validate and get other parameters.
                string leaveType = cboLeaveType.Text.Trim();
                string totalBalance = txttotalleave.Text.Trim();
                string month = cboMonth.Text;
                string noOfDays = NoOfDays.Text;
                string leaveDate = dtpLeavedate.Value.ToString("yyyy-MM-dd");
                string leaveTime = dtpLeaveTime.Value.ToString("HH:mm:ss");
                string endDate = dtpEndDate.Value.ToString("yyyy-MM-dd");
                string endTime = dtpEndTime.Value.ToString("HH:mm:ss");
                string sanctionedLeave = txtLSanctioned.Text;
                string availedLeave = txtLAvailed.Text.Trim();
                string balance = txtBalance.Text;
                string reason = txtReasons.Text;

                // Build the SQL update query.
                string updateQuery = @"UPDATE Facultyleave SET
                                Faculty_ID = @Faculty_ID,
                                LeaveType = @LeaveType,
                                TotalBalance = @TotalBalance,
                                Month = @Month,
                                Days = @Days,
                                LeaveDate = @LeaveDate,
                                LeaveTime = @LeaveTime,
                                EndDate = @EndDate,
                                EndTime = @EndTime,
                                SancationedLeave = @SancationedLeave,
                                AvailedLeave = @AvailedLeave,
                                Balance = @Balance,
                                Reason = @Reason
                                WHERE Faculty_ID = @Faculty_ID
                                AND LeaveID = (SELECT MAX(LeaveID) FROM FacultyLeave WHERE Faculty_ID = @Faculty_ID);";

                using (var conn = DatabaseAccess.ConnOpen())
                    using (var cmd = new SqlCommand(updateQuery, conn))
                        // Add parameters and values.
                        cmd.Parameters.AddWithValue("@Faculty_ID", facultyID);
                        cmd.Parameters.AddWithValue("@LeaveType", leaveType);
                        cmd.Parameters.AddWithValue("@TotalBalance", totalBalance);
                        cmd.Parameters.AddWithValue("@Month", month);
                        cmd.Parameters.AddWithValue("@Days", noOfDays);
                        cmd.Parameters.AddWithValue("@LeaveDate", leaveDate);
                        cmd.Parameters.AddWithValue("@LeaveTime", leaveTime);
                        cmd.Parameters.AddWithValue("@EndDate", endDate);
                        cmd.Parameters.AddWithValue("@EndTime", endTime);
                        cmd.Parameters.AddWithValue("@SancationedLeave", sanctionedLeave);
                        cmd.Parameters.AddWithValue("@AvailedLeave", availedLeave);
                        cmd.Parameters.AddWithValue("@Balance", balance);
                        cmd.Parameters.AddWithValue("@Reason", reason);

                        int result = cmd.ExecuteNonQuery();

                        // If the update was successful, update the DataGridView and show success message.
                        if (result > 0)
                            int updatedLeaveID = Convert.ToInt32(cmd.ExecuteScalar());

                            // Update the DataGridView row.
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[0].Value = updatedLeaveID; // LeaveID
                                                                                                        // ...

                            // Calculate updated balance and availed leave
                            int originalTotalBalance = Convert.ToInt32(totalBalance);
                            int originalAvailedLeave = Convert.ToInt32(txtLAvailed.Text);
                            int updatedNoOfDays = Convert.ToInt32(noOfDays);
                            int updatedBalance = originalTotalBalance - updatedNoOfDays;
                            int updatedAvailedLeave = originalAvailedLeave + updatedNoOfDays;

                            //int updatedLeaveID = Convert.ToInt32(cmd.ExecuteScalar());

                            // Update the DataGridView row.
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[0].Value = updatedLeaveID; // LeaveID
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[1].Value = facultyID; // Faculty ID
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[2].Value = leaveType; // Leave Type
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[3].Value = updatedBalance; // Total Balance
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[4].Value = month; // Month
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[5].Value = updatedNoOfDays; // No of Days
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[6].Value = leaveDate; // Leave Date
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[7].Value = leaveTime; // Leave Time
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[8].Value = endDate; // End Date
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[9].Value = endTime; // End Time
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[10].Value = sanctionedLeave;
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[10].Value = sanctionedLeave; // Sanctioned Leave
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[11].Value = updatedAvailedLeave; // Availed Leave
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[12].Value = balance; // Balance
                            dgvFacultyLeaveList.Rows[selectedRowIndex].Cells[13].Value = reason; // Reason

                            // Refresh the DataGridView.

                            // Clear the input fields.
                            txtID.Text = "";
                            cboLeaveType.SelectedIndex = -1;
                            txttotalleave.Text = "";
                            cboMonth.SelectedIndex = -1;
                            NoOfDays.Text = "";
                            dtpLeavedate.Value = DateTime.Now;
                            dtpLeaveTime.Value = DateTime.Now;
                            dtpEndDate.Value = DateTime.Now;
                            dtpEndTime.Value = DateTime.Now;
                            txtLSanctioned.Text = "";
                            txtLAvailed.Text = "";
                            txtBalance.Text = "";
                            txtReasons.Text = "";
                            // Show a success message.
                            MessageBox.Show("Record updated successfully!");
            catch (Exception ex)
                // Handle the exception gracefully.
                // For example, log the exception and display a more user-friendly message to the user.
                MessageBox.Show("Error updating the record: " + ex.Message);
            } }

What I have tried:

this is the code of my update button for Leave Module i have problem that when i want to update the leave for staff member so it calculate the previous value which is in NoOfDays textbox suppose i add leave for staff member the total balance = 10 . i add 1 leave than remaining balance =9, availed =1. so than i want to update the leave so i edit it and i remove the value which is in the textbox of NoOfDay which is =1 and write 2 so it do like add 1+2 =3 and than make balance =7, availed =3. the expected outcome should be Remaining balance = 8, availed = 2. my NoOfDays.text textbox take the previous value i add a button also that make make it 0 but its also calculate the zero when i click on the remove button to make noofdays textbox 0 it again add one value like balance =9, availed =1 when i remove the value from noofdays textbox so its become zero than it make balance = 8, availed = 2.
Updated 12-Dec-23 6:11am
Richard MacCutchan 12-Dec-23 4:21am    
As we expalined in your previous question on the same subject, do not use strings for all your numeric, Date and Time values. Use proper types and avoid the mistakes you are making. Converting back and forth between text and numbers is a recipe for disaster.
jochance 30-Jan-24 19:33pm    
Unfortunately, you can't really set a type for a Text control so string->number conversion just has to happen. This looks like winforms/WPF.
Richard MacCutchan 31-Jan-24 3:52am    
That has nothing to do with my comment.
jochance 31-Jan-24 14:16pm    
If you say so... "do not use strings for all your numeric, Date and Time values"
Richard MacCutchan 1-Feb-24 4:40am    
Everyone who actually understands how databases operate also says so.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900