如何在数据网格视图C#Windows应用程序中保存复选框的选中状态 [英] How to save checked status for checkbox in data grid view c# windows application

查看:76
本文介绍了如何在数据网格视图C#Windows应用程序中保存复选框的选中状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C#Windows应用程序中工作,从SQL服务器到数据网格视图填充记录,并在每行中使用动态复选框功能。我想通过该特定行的复选框为某些目的选择选定的行。到现在为止,我成功实现了目标。但是我在保存已检查状态方面遇到了一个小问题,例如,我只想检查Name = Max的那些记录,我在该文本框中有一个文本框,我用Query

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

按名称过滤的代码:

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

如果我在名称过滤器文本框中输入Max,它将返回3条名称记录我从上面使用类似查询的max开始,就像我上面提到的代码。所以我只使用动态复选框检查3条记录中的2条记录,直到现在我的代码都可以完美运行。现在,我想检查名称从Ali开始的记录,现在当我在名称过滤器中通过名称文本框写ali时,它将返回行,其中名称类似于ali,但问题出在这里,它将删除我之前检查过的记录,因此我将如何保存max和ali行的检查记录:

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;


推荐答案

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

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

这篇关于如何在数据网格视图C#Windows应用程序中保存复选框的选中状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆