以编程方式选中DataGridView中的复选框

本文关键字:复选框 DataGridView 方式选 编程 | 更新日期: 2023-09-27 18:27:42

我看到了一些类似于这个问题的帖子,但我还没有给出答案,所以我想我会再次浮动它,看看会发生什么。。。

我正在使用ExcelDNA使用C#.NET将API与Excel集成。我有一个DataGridView,我想检查列表中已经存在的项。

以下代码在绑定到按钮单击事件时有效,但在方法中调用代码时无效。

private void SelectAllItems()
{
    foreach (DataGridViewRow row in itemsBySupplier.Rows)
    {
        DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)row.Cells["selectItem"];
        check.Value = check.TrueValue;
    }
}

我在其他地方也遇到了同样的问题:

foreach (DataGridViewRow row in itemsBySupplier.Rows)
{
    DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)row.Cells["selectItem"];
    string hid = row.Cells["Hid"].Value.ToString();
    if (Ws.ToCreate[_supplier].Count(i => i.Hid == hid) > 0)
    {
        check.Value = check.TrueValue;
    }
}

我已经研究了几个小时了,结果完全是空的。如有任何帮助,我们将不胜感激。

以编程方式选中DataGridView中的复选框

您可以通过将值设置为true来实现这一点。您不需要强制转换为复选框单元格。

    private void SelectAllItems()
    {
        foreach (DataGridViewRow row in itemsBySupplier.Rows)
        {
            // This will check the cell.
            row.Cells["selectItem"].Value = "true";
        }
    }
foreach (DataGridViewRow row in itemsBySupplier.Rows)
{
    string hid = row.Cells["Hid"].Value.ToString();
    if (Ws.ToCreate[_supplier].Count(i => i.Hid == hid) > 0)
    {
        row.Cells["selectItem"].Value = "true";                        
    }
}