DataGridView复选框列 - 值和功能

19
我在C#窗体中的DataGridView中添加了一个复选框列。该功能需要是动态的——您选择一个客户,这将显示出所有可服务的项目,然后您选择本次想要服务的项目。
无论如何,现在代码将在DGV的开头添加一个复选框。我需要知道以下内容:
1)如何使整个列默认为“已选中”? 2)当我点击DGV下面的按钮时,如何确保我只获取“已选中”行的值?
以下是插入列的代码:
DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
            doWork.HeaderText = "Include Dog";
            doWork.FalseValue = "0";
            doWork.TrueValue = "1";
            dataGridView1.Columns.Insert(0, doWork);

那么接下来该怎么做呢?非常感谢任何帮助!

11个回答

42
  1. 没有直接的方法来实现这一点。一旦将数据放入网格中,您可以通过以下方式循环遍历行并检查每个框:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    row.Cells[CheckBoxColumn1.Name].Value = true;
}
  • Click事件可能会像这样:

  • private void button1_Click(object sender, EventArgs e)
    {
        List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (Convert.ToBoolean(row.Cells[CheckBoxColumn1.Name].Value) == true)
            {
                rows_with_checked_column.Add(row);
            }
        }
        // Do what you want with the check rows
    }
    

    1
    非常感谢!这真的很有用,但只有一件事...当我到达那个点时,要从选中的行获取信息,我该如何从特定单元格获取信息(例如所有选中单元格中第2列的单元格值)?另外...你似乎真的很懂C#,有什么书可以推荐吗?谢谢。 - David Archer
    其实,不用担心了,我已经找到方法解决了。再次感谢你的帮助! - David Archer
    1
    很高兴你找到了答案。至于推荐一本学习C#的书,我不知道有哪些好的。我经常使用msdn(http://msdn.microsoft.com/en-us/library/ms229335.aspx)网站查找方法/属性/描述/示例等,所以我认为那可能是最好的参考资料,还有Stack Overflow ;) - SwDevMan81
    如果您连续点击复选框2、3次,它会抛出异常,无法将“Checked”转换为布尔值。最初它显示的值为true,然后将其更改为checked。 - PUG
    if 语句中的 == true 是什么意思? - galaxy001

    15
    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
        ch1 = (DataGridViewCheckBoxCell)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0];
    
        if (ch1.Value == null)
            ch1.Value=false;
        switch (ch1.Value.ToString())
        {
            case "True":
                ch1.Value = false;
                break;
            case "False":
                ch1.Value = true;
                break;
        }
        MessageBox.Show(ch1.Value.ToString());
    }
    

    在DataGridView中查找复选框是否被选中的最佳解决方案。


    谢谢,非常好用!只有当单元格具有复选框时才处理事件:// .... DataGridView dgv = (DataGridView)sender; if (dgv.CurrentCell.GetType() != typeof(DataGridViewCheckBoxCell)) { return; } // ... - illagrenan
    1
    谢谢@Nazeer, 对你代码片段做了一点调整,原先是这样的:if (ch1.Value == null) ch1.Value = false; ch1.Value = !(bool)ch1.Value;现在可以简化成:switch (ch1.Value.ToString()) { case "True": ch1.Value = false; break; case "False": ch1.Value = true; break; } - Abbas Palash

    5

    在没有必要遍历所有记录的情况下,我花了很长时间才弄清楚如何完成此操作。我有一个绑定的DataGridView源,除了复选框列之外,所有字段都已绑定。因此,我不需要使用循环添加每一行,也不想为此创建一个循环。经过多次尝试,我终于做到了。而且这实际上也很简单:

    首先,您需要向项目中添加一个新的.cs文件,其中包含自定义复选框单元格,例如:

    DataGridViewCheckboxCellFilter.cs:

    using System.Windows.Forms;
    
    namespace MyNamespace {
        public class DataGridViewCheckboxCellFilter : DataGridViewCheckBoxCell {
            public DataGridViewCheckboxCellFilter() : base() {
                this.FalseValue = 0;
                this.TrueValue = 1;
                this.Value = TrueValue;
            }
        }
    }
    

    在此之后,在您的GridView上添加复选框列,您需要执行以下操作:
    // add checkboxes
    DataGridViewCheckBoxColumn col_chkbox = new DataGridViewCheckBoxColumn();
    {
        col_chkbox.HeaderText = "X";
        col_chkbox.Name = "checked";
        col_chkbox.CellTemplate = new DataGridViewCheckboxCellFilter();                
    }
    this.Columns.Add(col_chkbox);
    

    就是这样!每当您的复选框添加到新行中时,它们都将被设置为“true”。 享受吧!


    我最喜欢这个实现方式。从性能方面来看似乎是最快的。你不需要进行任何循环。 - Jack Fairfield
    这是问题的答案。谢谢。 - EllieK

    3
    如果您在CellContentClick事件中尝试它
    使用:
    dataGridView1.EndEdit();  //Stop editing of cell.
    MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
    

    3
    这个问题的一句话答案如下:
    List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();
    

    +1正是我在寻找的,感谢Rob。注意:我之前一直遇到一个Object not set DBNUll异常,所以我把你的代码改成了这样:'// 在一个Lamba好方法中找到所选行 - 不使用Deferred Execution! List<DataGridViewRow> selectedSeriesCodes = gridSeriesList.Rows.Cast<DataGridViewRow>().Where(g => !string.IsNullOrEmpty(g.Cells["Selected"].Value.ToString()) && Convert.ToBoolean(g.Cells["Selected"].Value) == true).ToList();' - Jeremy Thompson

    1
    如果您的GridView包含多个复选框....您可以尝试这个....
    Object[] o=new Object[6];
    
    for (int i = 0; i < dgverlist.RowCount; i++)
    {
        for (int j = 2; j < dgverlist.ColumnCount; j++)
        {
            DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
            ch1 = (DataGridViewCheckBoxCell)dgverlist.Rows[i].Cells[j];
    
            if (ch1.Value != null)
            {
               o[i] = ch1.OwningColumn.HeaderText.ToString();
    
                MessageBox.Show(o[i].ToString());
            }
        }
    }
    

    1

    1)如何使整个列默认为“已选中”?

    var doWork = new DataGridViewCheckBoxColumn();
    doWork.Name = "IncludeDog" //Added so you can find the column in a row
    doWork.HeaderText = "Include Dog";
    doWork.FalseValue = "0";
    doWork.TrueValue = "1";
    
    //Make the default checked
    doWork.CellTemplate.Value = true;
    doWork.CellTemplate.Style.NullValue = true;
    
    dataGridView1.Columns.Insert(0, doWork);
    

    2) 如何确保我只从“已选中”行获取值?

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.IsNewRow) continue;//If editing is enabled, skip the new row
    
        //The Cell's Value gets it wrong with the true default, it will return         
        //false until the cell changes so use FormattedValue instead.
        if (Convert.ToBoolean(row.Cells["IncludeDog"].FormattedValue))
        {
            //Do stuff with row
        }
    }
    

    0
    如果您将 SQL 数据库中的此列(位)设置为数据类型,则应编辑此代码。
    DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
    doWork.HeaderText = "Include Dog";
    doWork.FalseValue = "0";
    doWork.TrueValue = "1";
    dataGridView1.Columns.Insert(0, doWork);
    

    使用这个

    DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
    doWork.HeaderText = "Include Dog";
    doWork.FalseValue = "False";
    doWork.TrueValue = "True";
    dataGridView1.Columns.Insert(0, doWork);
    

    0

    这非常简单

    DataGridViewCheckBoxCell checkedCell = (DataGridViewCheckBoxCell) grdData.Rows[e.RowIndex].Cells["grdChkEnable"];
        
    bool isEnabled = false;
    if (checkedCell.AccessibilityObject.State.HasFlag(AccessibleStates.Checked))
    {
        isEnabled = true;
    }
    if (isEnabled)
    {
       // do your business process;
    }
    

    0

    测试列是否被选中:

    for (int i = 0; i < dgvName.Rows.Count; i++)
    {
        if ((bool)dgvName.Rows[i].Cells[8].Value)
        {
        // Column is checked
        }
    }
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接