1

可能重复:
DataGridViewCheckBoxCell 如何在表单加载期间设置时显示已选中

我在 C#-WinForms 项目中遇到了 DataGridView 的问题。

我用本地数据库中的数据填充它。此外,我添加了一个未绑定到任何数据的 CheckBoxColumn。我使用它来根据选中的行过滤 ListBox。这一切都放在对话框表单上 TabControl 的第二页上,并且运行良好。

现在我想根据打开表单时通过的字符串列表以编程方式选择行。我试过这段代码:

foreach (string pre in preselect)
{
    foreach (DataGridViewRow row in dgvProtFunc.Rows)
    {
        if ((string)row.Cells[2].Value == pre)
        {
            ((DataGridViewCheckBoxCell)row.Cells[0]).Value = true;
        }
    }
}

设置值,然后触发过滤适用于表单加载。但是,未选中复选框。检查一个时,所有其他值都将丢失。那很糟糕,因为我必须使用这样的预选。这些是其他 DataGridView 事件处理程序:

private void dgvProtFunc_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dgvProtFunc.IsCurrentCellDirty)
    {
        dgvProtFunc.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

private void dgvProtFunc_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (!FormLoadCheck)
    {
        string data = string.Empty;
        ptSelectList.Clear();
        foreach (DataGridViewRow row in dgvProtFunc.Rows)
        {
           if (row.Cells[0].Value != null && Convert.ToBoolean(row.Cells[0].Value) == true)
           {
               ptSelectList.Add(Convert.ToInt32(row.Cells[1].Value));
           }
           data += row.Cells[0].Value;
        }
        ptSelectList.Sort();
        FilterRelais(ptSelectList.ToArray());
        MessageBox.Show(data);
   }
}

谁能解释这种行为?有什么解决办法吗?

4

0 回答 0