有人可以帮助我为什么它不起作用吗?
我有一个checkbox
如果我点击它,
这应该取消选中 datagridview 内的所有复选框,这些复选框在包含用户选择的复选框之前已选中。
这是代码:
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;
}
}
}
不应选择该复选框。应该检查一下。
这是添加的列
DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckBox chk = new CheckBox();
CheckboxColumn.Width = 20;
datagridview1.Columns.Add(CheckboxColumn);
看着这个MSDN 论坛发帖 http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/74df79a9-87ad-4cec-8502-3a357015558d它建议将单元格的值与细胞真值 http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcheckboxcell.truevalue.aspx.
因此,根据示例,您的代码应该如下所示:(这是完全未经测试的)
编辑:似乎未绑定 DataGridViewCheckBox 的 Cell.TrueValue 的默认值为 null,您需要在列定义中设置它。
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;
}
}
}
此代码的工作注释是在构造函数中设置 TrueValue 和 FalseValue,并检查 null:
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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)