Saving changes made to ASP.Net gridview webform cell is not working

Have a nice day ahead. I am having a problem in saving the contents of gridview cells to database. Here’s the scenario. My gridview contains timesheet of employee. The employee can move the timesheet cell data from one cell to another but cannot tamper its data. I use javascript to right-click to a cell and left-click to move the content of a cell to a desired cell. It is working fine. The problem is when I save the contents of gridview after the modifications made to cells. The original contents of cell is saved to database, not the modified contents of the gridview. I am asking for your brilliant minds to help me solve my problem.

Here’s my javascript code for moving cell content to another cell:

<script>
        $(document).ready(function () {
            var sourceCellIndex = -1; // Variable to store the index of the source cell

            // Function to handle right-click on a cell
            $(document).on("contextmenu", "#<%= gvTimesheet.ClientID %> td", function (e) {
            e.preventDefault(); // Prevent the default context menu
            sourceCellIndex = $(this).index(); // Get the index of the clicked cell
            alert("Selected Data: " + $(this).text()); // Display an alert with the text of the clicked cell
            return false;
        });

        // Function to handle left-click on a cell
        $(document).on("click", "#<%= gvTimesheet.ClientID %> td", function () {
            if (sourceCellIndex !== -1) { // Check if a source cell has been selected
                var destinationCellIndex = $(this).index(); // Get the index of the clicked cell

                // Transfer the text from the source cell to the destination cell
                var sourceText = $("tr").eq($(this).closest("tr").index()).find("td").eq(sourceCellIndex).text();
                $(this).text(sourceText); // Set the text of the destination cell
                $("tr").eq($(this).closest("tr").index()).find("td").eq(sourceCellIndex).text(""); // Clear the text of the source cell

                // Update hidden fields based on source and destination cell indices
                var sourceHiddenField, destinationHiddenField;
                if (sourceCellIndex === 2) {
                    sourceHiddenField = $("#<%= hiddenInAM.ClientID %>");
                } else if (sourceCellIndex === 3) {
                    sourceHiddenField = $("#<%= hiddenOutAM.ClientID %>");
                }
                if (destinationCellIndex === 4) {
                    destinationHiddenField = $("#<%= hiddenInPM.ClientID %>");
                } else if (destinationCellIndex === 5) {
                    destinationHiddenField = $("#<%= hiddenOutPM.ClientID %>");
                }

                if (sourceHiddenField && destinationHiddenField) {
                    destinationHiddenField.val(sourceText); // Update the value of the destination hidden field
                    sourceHiddenField.val(""); // Clear the value of the source hidden field
                }

                // Call captureChanges to capture the modified data
                var modifiedData = captureChanges();

                // Call saveChangesToServer to save the modified data
                saveChangesToServer(modifiedData);
                /*alert("Data transferred successfully!");*/

                sourceCellIndex = -1; // Reset the source cell index
            }
        });
    });
    </script>

Code behind:

public void saveTimesheet()
        {
            try
            {
                SqlConnection conn = new SqlConnection(Conn.strCon);
foreach (GridViewRow row in gvTimesheet.Rows)
                    {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
string lblDate = row.Cells[0].Text;
                            string lblDay = row.Cells[1].Text;

                            amIn = row.Cells[2].Text;
                            amOut = row.Cells[3].Text;
                            pmIn = row.Cells[4].Text;
                            pmOut = row.Cells[5].Text;
SqlCommand cmd1 = new SqlCommand("INSERT INTO tbl_timesheet(compcde,empno,empnem,paytype,cstctr,bioDate,bioDay,inAM,outAM,inPM,outPM,reghrs,OT,remarks,firstApprover,secondApprover,status) VALUES (@compcde,@empno,@empnem,@paytype,@cstctr,@bioDate,@bioDay,@inAM,@outAM,@inPM,@outPM,@reghrs,@OT,@remarks,@firstApprover,@secondApprover,@status) ", conn);
                                cmd1.Parameters.AddWithValue("@compcde", comp_cde);
                                cmd1.Parameters.AddWithValue("@empno", IDNo);
                                cmd1.Parameters.AddWithValue("@empnem", name);
                                cmd1.Parameters.AddWithValue("@paytype", paytype);
                                cmd1.Parameters.AddWithValue("@cstctr", costctr);
                                cmd1.Parameters.AddWithValue("@bioDate", lblDate);
                                cmd1.Parameters.AddWithValue("@bioDay", lblDay);
                                cmd1.Parameters.AddWithValue("@inAM", amIN);
                                cmd1.Parameters.AddWithValue("@outAM", amOUt);
                                cmd1.Parameters.AddWithValue("@inPM", pmIN);
                                cmd1.Parameters.AddWithValue("@outPM", pmOUt);
if (double.TryParse(lblOTHrs, out OTHrs))
                                {
                                    if (OTHrs > 0)
                                    {
                                        cmd1.Parameters.AddWithValue("@reghrs", 8.0);
                                        cmd1.Parameters.AddWithValue("@OT", OTHrs);
                                    }
                                    else
                                    {
                                        cmd1.Parameters.AddWithValue("@reghrs", lblRegHrs);
                                        cmd1.Parameters.AddWithValue("@OT", 0.0);
                                    }
                                }
                                else
                                {
                                    cmd1.Parameters.AddWithValue("@reghrs", lblRegHrs);
                                    cmd1.Parameters.AddWithValue("@OT", 0.0);
                                }
                                cmd1.Parameters.AddWithValue("@remarks", lblRemarks);
                                cmd1.Parameters.AddWithValue("@firstApprover", txtApprover.Text);
                                cmd1.Parameters.AddWithValue("@secondApprover", txtApprover2.Text);
                                cmd1.Parameters.AddWithValue("@status", "For Approval");
                               
                                conn.Open();
                                cmd1.ExecuteNonQuery();
                                conn.Close();
}
}
}
}

I tried to add another javascript to catch the changes made to cells but this code is not working.

javascript code:

<script>
        // Example usage when the user clicks a "Save" button
        $('#btnSave').click(function () {
            // Capture changes made by the user
            var modifiedData = captureChanges();

            // Send modified data to the server for saving
            saveChangesToServer(modifiedData);
        });

        // Function to capture changes made by the user
        function captureChanges() {
            var modifiedData = []; // Array to store modified timesheet data

            // Loop through each row in the GridView
            $('#<%= gvTimesheet.ClientID %> tr').each(function (index, row) {
                var rowData = []; // Array to store data for the current row

                // Loop through each cell in the row
                $(row).find('td').each(function (cellIndex, cell) {
                    // Check if the cell has been modified (you may need to implement your own logic here)
                    // For example, check if the cell's text has changed from its original value

                    // Retrieve the updated value from the cell
                    var updatedValue = $(cell).text();

                    // Add the updated value to the rowData array
                    rowData.push(updatedValue);
                });

                // Add the rowData array to the modifiedData array
                modifiedData.push(rowData);
            });

            // Return the modifiedData array containing all the changes made by the user
            return modifiedData;
        }

        // Function to send modified data to the server for saving
        function saveChangesToServer(modifiedData) {
            // Convert modified data to JSON
            var jsonData = JSON.stringify(modifiedData);

            // Make an AJAX call to the server-side method to save the data
            $.ajax({
                type: 'POST',
                url: 'Create_Timesheet.aspx/SaveTimesheetData',
                data: { jsonData: jsonData },
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (response) {
                    // Handle success response from the server
                    alert(response.d); // Display success message
                },
                error: function (xhr, status, error) {
                    // Handle error response from the server
                    console.error(error); // Log the error to the console
                    alert('Error occurred while saving data. Please try again.'); // Display error message
                }
            });
        }



    </script>```

Code behind:

[WebMethod]
public static string SaveTimesheetData(string jsonData)
{
try
{

            // Deserialize the JSON data received from the client
            // For simplicity, let's assume jsonData is an array of arrays representing the modified timesheet data
            // You'll need to adjust this based on your actual JSON structure
            string[][] modifiedTimesheetData = Newtonsoft.Json.JsonConvert.DeserializeObject<string[][]>(jsonData);

            // Process the modified timesheet data and update the database accordingly
            foreach (var rowData in modifiedTimesheetData)
            {
                amIn= rowData[0]; // Assuming the first element represents timeIn-AM
                amOut= rowData[1]; // Assuming the second element represents timeOut-AM
                pmIn= rowData[2]; // Assuming the third element represents timeIn-PM
                pmOut= rowData[3];
                
            }

            // Return a success message to the client
            return "Timesheet data saved successfully!";
        }
        catch (Exception ex)
        {
            // Log the exception or handle it as needed
            return "Error saving timesheet data: " + ex.Message;
        }
    }
I hope that you can help find a way to solve this. Thank you in advance and God bless you all...

New contributor

ChenXiaoXi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật