繁体   English   中英

如何检查数据网格视图中的复选框是否已选中

[英]How to check whether Check box inside data grid view is checked or not

如何检查datagridview中的复选框的bool条件。 我希望如果选中则为true如果未选中则为false 谁能帮我。

是否可以在dataGridView_CellContentClick处理此问题

这是在MSDN页DataGridView的解决一点点在这里这里

他们特别说:

对于DataGridViewCheckBoxCell中的单击,此事件在复选框更改值之前发生,因此如果您不想根据当前值计算预期值,则通常会处理DataGridView.CellValueChanged事件。 因为该事件仅在提交用户指定的值时发生(通常在焦点离开单元格时发生),所以还必须处理DataGridView.CurrentCellDirtyStateChanged事件。 在该处理程序中,如果当前单元格是复选框单元格,则调用DataGridView.CommitEdit方法并传入Commit值。

所以他们建议不要使用CellClick类型的事件(因为他们从不推送值直到你离开单元格),而是使用CurrentCellDirtyStateChanged和CommitEdit方法。

所以你最终得到:

dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);

void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].Name == "CB")
    {
        MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());    
    }
}

void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

至于获取选中的值 - 这只是DataGridViewCheckBoxCell的Value属性。

所以,如果你去:

dataGridView1.Rows[rowindex].Cells[cellindex].Value 

你得到一个与复选框相对应的布尔值(在提交更改后)。

它100%工作。

 private void grd_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            grd.CommitEdit(DataGridViewDataErrorContexts.Commit);
            bool Result = Convert.ToBoolean((grd[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell).Value);
        }

如果在设计器中定义了复选框,则可以简单地查看复选框的名称并检查其“checked”属性是否为true / false。

但我怀疑你是通过代码将复选框添加到数据网格?

在这种情况下,你必须保存对somwhere复选框的引用。 如果我在哪里你将我添加到datagrid的所有复选框添加到列表中,或者如果你想通过名称引用它们,我会将它们添加到字典中。

您还可以通过选择事件并单击属性面板中的小螺栓图标并找到checkedChanged事件并双击它来将事件绑定到Checked_Changed事件复选框。

在事件代码中,您可以通过键入以下内容来获取单击的复选框:CheckBox mycheckbox = sender作为CheckBox;

然后引用mycheckbox.checked来获取bool,如果它已经检查过。

您可以尝试以这种方式获取此信息,例如,如果您根据索引循环网格,则可以找到已检查状态。

bool IsChecked = Convert.ToBoolean((dataGridView1[ColumnIndex, RowIndex] as DataGridViewCheckBoxCell).FormattedValue))
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var checkcell = new DataGridViewCheckBoxCell();
    checkcell.FalseValue = false;
    checkcell.TrueValue = true;
    checkcell.Value = false;
    dataGridView1[0, 0] = checkcell; //Adding the checkbox

    if (((bool)((DataGridViewCheckBoxCell)dataGridView1[0, 0]).Value) == true)
    {
        //Stuff to do if the checkbox is checked
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM