以编程方式循环访问DatagridView并选中复选框

6 c# windows datagridviewcheckboxcell

我有DataGridView绑定数据表我有相同的复选框.

我想导航或循环遍历datagridview并选中标记这些复选框,下面是我使用的语法.

foreach(DataGridViewRow dr in dgvColumns.Rows)
{
    DataGridViewCheckBoxCell checkCell =
        (DataGridViewCheckBoxCell)dr.Cells["CheckBoxes"];
    checkCell.Value=1;
    //Also tried checkCell.Selected=true;
    //Nothing seems to have worked.!
}
Run Code Online (Sandbox Code Playgroud)

小智 11

以下为我工作,它完全检查了复选框:)

foreach (DataGridViewRow row in dgvDataGridView.Rows)
{
    ((DataGridViewCheckBoxCell)row.Cells[0]).Value = true;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 3

如果它绑定到 a DataTable,您可以不处理模型(表)吗?这DataGridView是一个视图...

尝试循环表中的行,设置值。例如(如下) - 请注意,我不更新DataGridView- 只是DataTable

using System;
using System.Data;
using System.Windows.Forms;

static class Program
{
    [STAThread]
    static void Main()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Selected", typeof(bool));
        table.Rows.Add("Fred", false);
        table.Rows.Add("Jo", false);
        table.Rows.Add("Andy", true);

        Button btn = new Button();
        btn.Text = "Select all";
        btn.Dock = DockStyle.Bottom;
        btn.Click += delegate
        {
            foreach (DataRow row in table.Rows)
            {
                row["Selected"] = true;
            }
        };

        DataGridView grid = new DataGridView();
        grid.Dock = DockStyle.Fill;
        grid.DataSource = table;

        Form form = new Form();
        form.Controls.Add(grid);
        form.Controls.Add(btn);
        Application.Run(form);
    }
}
Run Code Online (Sandbox Code Playgroud)