How to save checked status for checkbox in data grid view c# windows application

心不动则不痛 提交于 2019-12-23 07:05:00

问题


I am working in c# windows application populate record from sql server to data grid view, with dynamic checkbox facility in each row. i want to select selected rows for some purpose via checkbox of that particular row. till now i successfully achieve my target. but i'm facing a minor issue regarding saving a checked status, Example i want to check only those records whose Name = Max i have a textbox in that textbox i call text chnage event with like Query

Code for Filter by name:

 try
        {
            SqlCommand cmd = null;
            SqlConnection con = null; Ranks rank = new Ranks();
            con = new SqlConnection(cs.DBcon);
            con.Open();
            cmd = con.CreateCommand();
            cmd.CommandText = "Select * from Records where Name like @Name order by Pno";
            cmd.Parameters.AddWithValue("@Name", "%" + FilterByNameTextbox.Text.Trim() + "%");
            SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter1.Fill(dt);

            dataGridView1.DataSource = dt;
            Make_fields_Colorful();
        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }

if i write Max in filter by name textbox it would return 3 records with name starts with max using like query as i mention code above. so i only check 2 records out of 3 using dynamic checkbox, till now my code runs perfectly. Now i want to check records which name starts from Ali, now when i write ali in my filter by name textbox it will return rows where name like ali , but problem comes here it will remove my previous checked records, so how i would able to save checked records for both max and ali's rows:

Code for adding dynamic checkboxes in each row

   DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
        checkBoxColumn.Name = "checkBoxColumn";
        checkBoxColumn.DataPropertyName = "Report";
        checkBoxColumn.HeaderText = "Report";
        dataGridView1.Columns.Insert(10, checkBoxColumn);
        dataGridView1.RowTemplate.Height = 100;
        dataGridView1.Columns[10].Width = 50;

回答1:


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

Step 1

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

Step 2

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);
    }
}

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();
        }
    }

Step 3

Create SQL Server Stored Procedure to save the changes

Eg.

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


来源:https://stackoverflow.com/questions/54642434/how-to-save-checked-status-for-checkbox-in-data-grid-view-c-sharp-windows-applic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!