Check checkboxes in DataGridView programmatically

BadAsstronaut picture BadAsstronaut · Oct 23, 2014 · Viewed 7.9k times · Source

I have seen a few posts similar to this issue, but I haven't come up with my answer so, I thought I would float it again to see what comes up...

I am using ExcelDNA to integrate an API with Excel using C#.NET. I have a DataGridView, and I would like to check items that already exist on a list.

The following code works when tied to a button-click event, but NOT when the code is called in a method.

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

I am running into the same issue elsewhere, too:

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;
    }
}

I've been researching this for a few hours, coming up completely empty. Any help would be greatly appreciated.

Answer

deathismyfriend picture deathismyfriend · Oct 23, 2014

You can do this by setting the value to true. You do not need to cast to a checkbox cell.

    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";                        
    }
}