且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在数据网格视图C#Windows应用程序中保存复选框的选中状态

更新时间:2023-10-19 21:42:04

为了使复选框选择保持不变,您将要求保存每一行的复选框状态。

In order persist with the check box selection, you would require to save the check box state for each row.

步骤1

记录表中添加新列。
例如 BIT的CheckState (此处 BIT 用于存储布尔值的SQL Server列类型)

Add new column in Record table. eg. CheckState of BIT (Here BIT SQL Server Column Type which stores Boolean values)

第2步

现在添加代码以利用 CurrentCellDirtyStateChanged来拦截复选框状态更改 DataGridView 事件。
下面是示例代码;

Now add the code to intercept Check Box state change by utilizing the CurrentCellDirtyStateChanged event of the DataGridView. Below is the sample code;

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{

    if (dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
    {
        bool checkVal = (Boolean)dataGridView1.CurrentCell.EditedFormattedValue;       // Check box state value
        int checkBoxState = checkVal ? 1 : 0;       // 1 - TRUE, 0 - FALSE

        // Now save the check box state change in the database table.

        // You would need a key field to distinguish the record in the DB table
        // As per the code you had provided you could do something similar to below, assuming that the Pno column is the key field/ unique

        int keyValue = (int)dataGridView1.CurrentRow.Cells["Pno"].Value;

        // Save the changes by passing checkBoxState and keyValue accordingly
        SetNewUploadFileForGrantAppID(checkBoxState, keyValue);
    }
}

调用SQL Server存储过程的函数。

Function to call the SQL Server stored procedure.

    private void SetNewUploadFileForGrantAppID(int pIntRecordKeyValue, int pIntCheckBoxStatus)
    {
        SqlConnection connection = new SqlConnection(cs.DBcon);

        try
        {
            SqlCommand sqlCommand = connection.CreateCommand();
            sqlCommand.CommandText = "dbo.usp_SetRecordCheckStatus";
            sqlCommand.CommandType = CommandType.StoredProcedure;

            sqlCommand.Parameters.AddWithValue("@pIntRecordKeyValue", pIntRecordKeyValue);
            sqlCommand.Parameters.AddWithValue("@pIntCheckBoxStatus", pIntCheckBoxStatus);
            connection.Open();
            sqlCommand.ExecuteScalar();
        }
        catch (Exception ex)
        {
            //LogError(ex);
        }
        finally
        {
            connection.Close();
            connection.Dispose();
        }
    }

步骤3

创建 SQL Server存储过程保存更改

例如。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[usp_SetRecordCheckStatus]
    @pIntRecordKeyValue INT,
    @pIntCheckBoxStatus INT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE dbo.Record
        SET CheckState = @pIntCheckBoxStatus
        WHERE Pno = @pIntCheckBoxStatus
END
GO