如何限制选择datagridview中的chekbox [英] How do I give limitations to select chekbox which is inside datagridview

查看:67
本文介绍了如何限制选择datagridview中的chekbox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

M尝试如下,但可能是错误的。请给我答案

M tried for this as below, but might be its wrong. Please suggect me answer

int count = 0;
            DataGridViewCheckBoxCell cell = new DataGridViewCheckBoxCell();
            cell = (DataGridViewCheckBoxCell)dgvTanksandCompartments.Rows[dgvTanksandCompartments.CurrentRow.Index].Cells[0];
           
           
           CheckBox box = (CheckBox)sender;           
            if (box.Checked)
            {
                count++;
            }

            if (count > 4)
            {
                MessageBox.Show("Error");
            }







我只想勾选5个复选框。如果用户选择了更多,则给出错误。




I Want to check only 5 checkbox. If user select more than that, then give error.

推荐答案

您可以保持在控件上检查的复选框的总数。



用于存储该信息的有用属性是标记,它将保存任何对象。因为整数是.NET中的对象,所以它会很好用。



这是一种方法
You could keep a running total of the number of checkboxes that are checked on your control.

A useful property for storing that information is the Tag which will hold any object. As integers are objects in .NET then it will do nicely.

Here's one way of doing it
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0 && ((DataGridView)sender).IsCurrentRowDirty)
    {
        int count = (this.dataGridView1.Tag != null) ? (int)this.dataGridView1.Tag : 0;

        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)((DataGridView)sender).Rows[e.RowIndex].Cells[0];
        bool cb = (bool)cell.EditedFormattedValue; //NB NOT .Value

        if (cb)
            count++;
        else
            count--;

        if (count > 5)
        {
            MessageBox.Show("You can only tick 5 items");
            ((DataGridView)sender).CancelEdit();
        }
        else
            this.dataGridView1.Tag = count;
    }
}



注意事项

- : CellContentClick 事件,这就是为什么我检查 IsCurrentRowDirty

- :cell.Value不返回您正在移动复选框的值,尽管您可以看到它已被勾选。所以使用 EditedFormattedValue 而不是

- :如果你不使用 .CancelEdit()然后勾选复选框!


Points to note
-: The CellContentClick event can be fired when the DGV is being populated, which is why I check for IsCurrentRowDirty
-: cell.Value doesn't return the value that you are moving the checkbox to, despite the fact you can "see" that it has been ticked. So use EditedFormattedValue instead
-: If you don't use .CancelEdit() then the checkbox remains ticked!


这篇关于如何限制选择datagridview中的chekbox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆