[英]How can I display the number of checked checkboxes in a textbox from a column in a datagridview?
I have a DataGridView with a CheckBox column in it. 我有一个带有CheckBox列的DataGridView。 (This is an inventory system.) The check is used to move serial numbers of items from one location to another in our company. (这是一个库存系统。)该检查用于在我们公司中将项目的序列号从一个位置移动到另一个位置。
I also have a textbox where, as of now, the employee enters the number of items he is moving, then checks the appropriate serial numbers, and moves the items. 我还有一个文本框,截至目前,员工输入他正在移动的项目数,然后检查相应的序列号,并移动项目。
I would like the number in the textbox to be generated depending on how many serial numbers are checked. 我想根据检查的序列号来生成文本框中的数字。 Is it even possible? 它甚至可能吗? I've tried about a hundred different solutions at this point and they all either end in strange errors, or give me no results whatsoever. 我已经尝试了大约一百种不同的解决方案,它们都以奇怪的错误结束,或者没有给我任何结果。
Untested, but this should be close enough. 未经测试,但这应该足够接近。 I read an article or ten about this once when I was having the same issue. 当我遇到同样的问题时,我读过一篇关于这篇的文章。 The trick is to commit the edit immediately when the box is clicked on, which will then trigger the CellValueChanged
event. 诀窍是在单击框时立即提交编辑,然后触发CellValueChanged
事件。 You can then pick up the count from there. 然后你可以从那里拿起计数。
This should update the textbox as you check and uncheck the checkbox: 这应该在您选中时取消选中文本框并取消选中该复选框:
private void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgv.IsCurrentCellDirty && dgv.CurrentCell.OwningColumn.Name == "MyCheckColumn")
dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) //just a guard for the header row
return;
if (dgv.Columns[e.ColumnIndex].Name == "MyCheckColumn")
textBox.Text = dgv.Rows.Cast<DataGridViewRow>().Count(r => Convert.ToBoolean(r.Cells["MyCheckColumn"].Value)).ToString();
}
Hopefully the Linq works. 希望Linq有效。 If not, you'll have to do it the old-fashioned foreach
way with a sum variable. 如果没有,你将不得不用一个sum变量以老式的foreach
方式来做。 I know the DataGridViewRowCollection
can be finicky sometimes. 我知道DataGridViewRowCollection
有时会很挑剔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.