无法在datagridview中选择行

时间:2011-05-26 18:02:13

标签: c# datagridview

我有一个方法可以在datagrid中选择行并更改checkboxcolumn的值:

foreach (DataGridViewRow gridRow in dataGridView1.Rows)
            {
                if (_selectedIDs != null)
                    foreach (long id in _selectedIDs)
                    {

                        gridRow.Selected = false;
                        if ((long)((DataRowView)gridRow.DataBoundItem)["ObjectD"] == id)
                            gridRow.Selected = true;
                    }

                if (_checkedIDs != null)
                    foreach (long id in _checkedIDs)
                    {

                        ((DataRowView)gridRow.DataBoundItem)["Choosen"] = 0;
                        if ((long)((DataRowView)gridRow.DataBoundItem)["ObjectD"] == id)
                            ((DataRowView)gridRow.DataBoundItem)["Choosen"]=true;
                    }
            }
            dataGridView1.Refresh();

当我调试这段代码时,我看到它进入行

gridRow.Selected = true;

((DataRowView)gridRow.DataBoundItem)["Choosen"]=true;

在quickwatch中,我看到这些行的属性已更改。

但执行此代码后,我仍然只选择了一行

有没有人知道这段代码有什么问题?

3 个答案:

答案 0 :(得分:2)

除了MultiSelect之外,您可能还需要确保数据绑定类实现INotifyPropertyChanged接口。
您也可以在开始循环之前设置selected = false,否则每次都会覆盖您的选择...

        foreach (DataGridViewRow gridRow in dataGridView1.Rows)
        {
            if (_selectedIDs != null)
                // *****
                gridRow.Selected = false;
                // *****
                foreach (long id in _selectedIDs)
                {

                    if ((long)((DataRowView)gridRow.DataBoundItem)["ObjectD"] == id)
                        gridRow.Selected = true;
                }

            if (_checkedIDs != null)
                foreach (long id in _checkedIDs)
                {

                    ((DataRowView)gridRow.DataBoundItem)["Choosen"] = 0;
                    if ((long)((DataRowView)gridRow.DataBoundItem)["ObjectD"] == id)
                        ((DataRowView)gridRow.DataBoundItem)["Choosen"]=true;
                }
        }

答案 1 :(得分:1)

确保DataGridView.MultiSelect属性设置为true。

答案 2 :(得分:0)

今天,我遇到了此错误,并已通过将Enabled设置为true

进行了修复
dataGridView1.Enabled = true;