C# 选中/取消选中 datagridview 上的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13338837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check/Uncheck a checkbox on datagridview
提问by user1647667
Can someone help me why it doesn't work?
I have a checkboxand if I click on it,
this should uncheck all the checkbox inside the datagridview which were checked before including the user selected checkbox.
有人可以帮助我为什么它不起作用吗?我有一个checkbox,如果我点击它,这应该取消选中 datagridview 中的所有复选框,这些复选框在包含用户选择的复选框之前已选中。
Here is the code:
这是代码:
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagridview1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Selected == true)
{
chk.Selected = false;
}
else
{
chk.Selected = true;
}
}
}
the checkbox should not be selected. it should be checked.
不应选中该复选框。应该检查一下。
here is the added column
这是添加的列
DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckBox chk = new CheckBox();
CheckboxColumn.Width = 20;
datagridview1.Columns.Add(CheckboxColumn);
采纳答案by Mark Hall
Looking at this MSDN Forum Postingit suggests comparing the Cell's value with Cell.TrueValue.
查看此MSDN 论坛发布它建议将 Cell 的值与Cell.TrueValue进行比较 。
So going by its example your code should looks something like this:(this is completely untested)
所以按照它的例子你的代码应该是这样的:(这是完全未经测试的)
Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition.
编辑:似乎未绑定 DataGridViewCheckBox 的 Cell.TrueValue 的默认值为空,您需要在 Column 定义中设置它。
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Value == chk.TrueValue)
{
chk.Value = chk.FalseValue;
}
else
{
chk.Value = chk.TrueValue;
}
}
}
This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null:
这段代码是在构造函数中设置 TrueValue 和 FalseValue 并检查空值的工作说明:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckboxColumn.TrueValue = true;
CheckboxColumn.FalseValue = false;
CheckboxColumn.Width = 100;
dataGridView1.Columns.Add(CheckboxColumn);
dataGridView1.Rows.Add(4);
}
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
if (chk.Value == chk.FalseValue || chk.Value == null)
{
chk.Value = chk.TrueValue;
}
else
{
chk.Value = chk.FalseValue;
}
}
dataGridView1.EndEdit();
}
}
回答by Mr_Green
The code you are trying here will flip the states (if true then became false vice versa) of the checkboxes irrespective of the user selected checkboxbecause here the foreachis selectingeach checkboxand performing the operations.
您在此处尝试的代码将翻转复选框的状态(如果为真则变为假,反之亦然),而与用户选择的复选框无关,因为这里foreach正在选择每个复选框checkbox并执行操作。
To make it clear, store the indexof the user selectedcheckbox before performing the foreachoperation and after the foreachoperation call the checkbox by mentioning the stored index and check it (In your case, make it True-- I think).
为了明确这一点,存储index的的用户选择复选框在执行前foreach操作和后foreach操作提一下存储索引调用的复选框,并检查它(在你的情况,让True-我认为)。
This is just logic and I am damn sure it is correct. I will try to implement some sample code if possible.
这只是逻辑,我敢肯定它是正确的。如果可能,我将尝试实现一些示例代码。
Modify your foreachsomething like this:
foreach像这样修改你的东西:
//Store the index of the selected checkbox here as Integer (you can use e.RowIndex or e.ColumnIndex for it).
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagridview1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Selected == true)
{
chk.Selected = false;
}
else
{
chk.Selected = true;
}
}
}
//write the function for checking(making true) the user selected checkbox by calling the stored Index
The above function makes all the checkboxes true including the user selected CheckBox. I think this is what you want..
上面的函数使所有复选框都为真,包括用户选择的 CheckBox。我想这就是你想要的..
回答by Kevin Denham
I was making my own version of a Checkbox to control a DataGridViewCheckBoxColumn when I saw this post wasn't actually answered. To set the checked state of a DataGridViewCheckBoxCell use:
当我看到这篇文章实际上没有得到回答时,我正在制作自己的 Checkbox 版本来控制 DataGridViewCheckBoxColumn。要设置 DataGridViewCheckBoxCell 的选中状态,请使用:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dataGridView1.Rows[row.Index].SetValues(true);
}
For anyone else trying to accomplish the same thing, here is what I came up with.
对于其他试图完成同样事情的人,这就是我想出的。
This makes the two controls behave like the checkbox column in Gmail. It keeps functionality for both mouse and keyboard.
这使得这两个控件的行为类似于 Gmail 中的复选框列。它保留了鼠标和键盘的功能。
using System;
using System.Windows.Forms;
namespace Check_UnCheck_All
{
public partial class Check_UnCheck_All : Form
{
public Check_UnCheck_All()
{
InitializeComponent();
dataGridView1.RowCount = 10;
dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvApps_CellContentClick);
this.dataGridView1.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.myDataGrid_OnCellMouseUp);
this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.myDataGrid_OnCellValueChanged);
this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
}
public int chkInt = 0;
public bool chked = false;
public void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
{
DataGridViewCheckBoxCell chk = dataGridView1.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(chk.Value) == true) chkInt++;
if (Convert.ToBoolean(chk.Value) == false) chkInt--;
if (chkInt < dataGridView1.Rows.Count && chkInt > 0)
{
checkBox1.CheckState = CheckState.Indeterminate;
chked = true;
}
else if (chkInt == 0)
{
checkBox1.CheckState = CheckState.Unchecked;
chked = false;
}
else if (chkInt == dataGridView1.Rows.Count)
{
checkBox1.CheckState = CheckState.Checked;
chked = true;
}
}
}
public void myDataGrid_OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
// End of edition on each click on column of checkbox
if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
{
dataGridView1.EndEdit();
}
dataGridView1.BeginEdit(true);
}
public void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
{
if (dataGridView1.CurrentCell.IsInEditMode)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.EndEdit();
}
}
dataGridView1.BeginEdit(true);
}
}
public void checkBox1_Click(object sender, EventArgs e)
{
if (chked == true)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
if (chk.Value == chk.TrueValue)
{
chk.Value = chk.FalseValue;
}
else
{
chk.Value = chk.TrueValue;
}
}
chked = false;
chkInt = 0;
return;
}
if (chked == false)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dataGridView1.Rows[row.Index].SetValues(true);
}
chked = true;
chkInt = dataGridView1.Rows.Count;
}
}
}
}
回答by Paul - Soura Tech LLC
While all the other answers are correct, I'll add another simple option which worked for me:
虽然所有其他答案都是正确的,但我将添加另一个对我有用的简单选项:
var r = dataGridView.Rows[rIndex];
var c = r.Cells[cIndex];
var value = (bool) c.Value;
c.Value = !value;
Compressed:
压缩:
var r = dataGridView.Rows[rIndex];
r.Cells[cIndex].Value = !((bool) r.Cells[cIndex].Value)
As long as cIndexrefers to a cell that is of type DataGridViewCheckBoxCell, this will work fine. Hope this helps somone.
只要cIndex引用类型为 的单元格DataGridViewCheckBoxCell,这将正常工作。希望这有助于某人。
回答by Ba Dao
you can try this code:
你可以试试这个代码:
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.CurrentRow.Cells[0];
dataGridView1.BeginEdit(true);
if (chk.Value == null || (int)chk.Value == 0)
{
chk.Value = 1;
}
else
{
chk.Value = 0;
}
dataGridView1.EndEdit();
回答by aravind kumar eruventy
Below Code is working perfect
下面的代码工作完美
Select / Deselect a check box column on data grid by using checkbox CONTROL
使用复选框 CONTROL 选择/取消选择数据网格上的复选框列
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked == false)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = chk.TrueValue;
}
}
else if(checkBox2.Checked==true)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = 1;
if (row.IsNewRow)
{
chk.Value = 0;
}
}
}
}
回答by aravind kumar eruventy
Try the below code it should work
试试下面的代码它应该可以工作
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked == false)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = chk.TrueValue;
}
}
else if (checkBox2.Checked == true)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = 1;
if (row.IsNewRow)
{
chk.Value = 0;
}
}
}
}
回答by Vikas Bansal
// here is a simple way to do so
//irate through the gridview
foreach (DataGridViewRow row in PifGrid.Rows)
{
//store the cell (which is checkbox cell) in an object
DataGridViewCheckBoxCell oCell = row.Cells["Check"] as DataGridViewCheckBoxCell;
//check if the checkbox is checked or not
bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
//if its checked then uncheck it other wise check it
if (!bChecked)
{
row.Cells["Check"].Value = true;
}
else
{
row.Cells["Check"].Value = false;
}
}
回答by Kees Boon
I had the same problem, and even with the solutions provided here it did not work. The checkboxes would simply not change, their Value would remain null. It took me ages to realize my dumbness:
我遇到了同样的问题,即使使用此处提供的解决方案,它也不起作用。复选框不会改变,它们的值将保持为空。我花了很长时间才意识到自己的愚蠢:
Turns out, I called the form1.PopulateDataGridView(my data)on the Form derived class Form1 beforeI called form1.Show(). When I changed up the order, that is to call Show()first, and then read the data and fill in the checkboxes, the value did not stay null.
事实证明,我打电话给form1.PopulateDataGridView(my data)窗体上派生类Form1上之前我打电话form1.Show()。当我更改顺序时,即先调用Show(),然后读取数据并填写复选框,该值没有保持为空。
回答by user6240633
Simple code for you it will work
简单的代码,它会起作用
private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgv.CurrentRow.Cells["ColumnNumber"].Value != null && (bool)dgv.CurrentRow.Cells["ColumnNumber"].Value)
{
dgv.CurrentRow.Cells["ColumnNumber"].Value = false;
dgv.CurrentRow.Cells["ColumnNumber"].Value = null;
}
else if (dgv.CurrentRow.Cells["ColumnNumber"].Value == null )
{
dgv.CurrentRow.Cells["ColumnNumber"].Value = true;
}
}

