选择datagridview中的复选框c#

我在datagridview中有一个下载列表,一个按钮和一个复选框。

我只是在datagridview上手动创建了一个复选框列。 (这是代码)

DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn(); CheckBox chk = new CheckBox(); CheckboxColumn.Width = 20; DataGrid1.Columns.Add(CheckboxColumn); 

这是程序。
第1步:用户将选中复选框上的项目。
第2步:用户将在下拉列表中选择项目。
第3步:用户点击按钮,它将更改项目名称
在下拉列表中选择的项目之前的复选框上。

这是我点击按钮后的问题,没有发生。

这是我的代码。

 private void button1_Click(object sender, EventArgs e) { int x = 0; foreach (DataGridViewRow item in this.DataGrid1.SelectedRows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)item.Cells[1]; if (chk.Selected) { // codes here } else { //code here } } x = x + 1; } 

*编辑**

我已经测试了这个,它绝对有效。 将其复制并粘贴到一个新项目中并使用它。 它应该可以帮助您达到您需要的位置。

  private void Form1_Load(object sender, EventArgs e) { DataGridViewCheckBoxColumn checkBox = new DataGridViewCheckBoxColumn(true); checkBox.HeaderText = "T/F"; dataGridView1.Columns.Add(checkBox); } private void button1_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0]; if (Convert.ToBoolean(chk.Value) == true) { MessageBox.Show("Value Is True"); } } } 

我建议打电话的第一件事:

 DataGrid1.EndEdit(); 

因为,我经历过,如果在从网格列中检索复选框值之前缺少此行,则有时输入不会按预期显示。

所以这样的事情:

 private void button1_Click(object sender, EventArgs e) { int x = 0; foreach (DataGridViewRow item in this.DataGrid1.SelectedRows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)item.Cells[1]; if (chk.Value) { // codes here for checked condition } else { //code here for UN-checked condition } } x = x + 1; }