网格视图问题中存在复选框和法院柱

问题描述 投票:0回答:1

问题是我在 gridview 中有很多行,但是当我选中某个或任何复选框时,我无法在计数列中添加 1。

我只需要一个代码,只要在 gridview 的任何行中选中一个特定的复选框,它就会自动将 1 添加到相应的计数值

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // Check if the clicked cell is in the "Attendance" column
    if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["Attendance"].Index)
    {
        // Toggle the "Attendance" value in the "Attend" column
        DataGridViewCheckBoxCell checkBoxCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;

        if (checkBoxCell != null) // Check if the cell exists
        {
            // Get the current value of the "Attend" cell (assuming it contains numeric data)
            int currentAttendance = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Attend"].Value);

            // Toggle the value between "1" and "0" when the checkbox is clicked
            int newAttendance = (currentAttendance == 0) ? 1 : 0;

            // Update the "Attend" cell with the new value
            dataGridView1.Rows[e.RowIndex].Cells["Attend"].Value = newAttendance;
        }
    }
}
c# checkbox gridview cell csharpcodeprovider
1个回答
0
投票

我尝试通过使用单元格集合的局部变量并使用模式匹配来稍微简化代码。

假设您有一个名为“Count”的列,我们可以添加行

int count = Convert.ToInt32(cells["Count"].Value);
cells["Count"].Value = count + 1;

在一起:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // Check if the clicked cell is in the "Attendance" column
    if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["Attendance"].Index)
    {
        var cells = dataGridView1.Rows[e.RowIndex].Cells;

        // Toggle the "Attendance" value in the "Attend" column
        if (cells[e.ColumnIndex] is DataGridViewCheckBoxCell checkBoxCell) // Check if the cell exists
        {
            // Get the current value of the "Attend" cell (assuming it contains numeric data)
            int currentAttendance = Convert.ToInt32(cells["Attend"].Value);

            // Toggle the value between "1" and "0" when the checkbox is clicked
            int newAttendance = (currentAttendance == 0) ? 1 : 0;

            // Update the "Attend" cell with the new value
            cells["Attend"].Value = newAttendance;

            // Increase Count
            int count = Convert.ToInt32(cells["Count"].Value);
            cells["Count"].Value = count + 1;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.