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

我有DataGridView由数据表绑定我有checkbox相同。

我想浏览或循环访问datagridview并勾选这些checkbox,下面是我使用的语法。

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.! } 

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

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

如果它绑定到一个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); } } 

有些东西是:

 foreach(DataGridViewRow dgvr in dgvColumns.Rows) { // Get the underlying datarow DataRow dr = ((DataRowView)dgvr.DataBoundItem).Row; // Update the appropriate column in the data row. // Assuming this is your column name in your // underlying data table dr["CheckBoxes"] = 1; } 

选择其值的行不会传递到底层的数据源,因此不会被保存。 数据源是Datatable。 它的datagridview的问题。

 using System.Collections.Generic; using System.Windows.Forms; namespace FindTheCheckedBoxes { public partial class Form1 : Form { List<TestObject> list = new List<TestObject>(); List<int> positionId = new List<int>(); public Form1() { InitializeComponent(); PopulateDataGrid(); foreach (DataGridViewRow row in dataGridView1.Rows) { if ((bool)row.Cells[0].Value == true) positionId.Add((int)row.Cells[1].Value); } // sets the window title to the columns found ... this.Text = string.Join(", ", positionId); } void PopulateDataGrid() { list.Add(new TestObject { tick = false, LineNum = 1 }); list.Add(new TestObject { tick = true, LineNum = 2 }); list.Add(new TestObject { tick = false, LineNum = 3 }); list.Add(new TestObject { tick = true, LineNum = 4 }); dataGridView1.DataSource = list; } } class TestObject { public bool tick { get; set; } public int LineNum { get; set; } } } 

这看起来像是你所需要的。 如果我的回答不正确,我很抱歉。 只是想帮助。