且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在datagrid视图virtualmode中排序或添加新项目或删除项目时,保持选择状态(多选)和复选框状态

更新时间:2023-12-04 10:47:58

所以你只想选择那些选中复选框的行:

 foreach(dgv.Rows中的DataGridViewRow行)
{
DataGridViewCheckBoxCell cell = row.Cells [1] as DataGridViewCheckBoxCell;
row.Selected =(bool)cell.Value;
}


(显然,您的复选框可能不是索引1)。


当用户更改复选框值时,您需要将其设置为选中,例如

 private void dgv_CellContentClick(object sender,DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell cell =(DataGridViewCheckBoxCell)dgv.CurrentCell;
dgv.Rows [e.RowIndex] .Selected =(bool)cell.EditedFormattedValue;
}


这种事情在wpf中相当容易,顺便说一下,你可以将选中的和复选框值绑定到同一个属性。


We are using datagrid view in virtual mode to display contacts having check box column and 4 new columns.

Unable to get previous selected and checked rows when sorting or new contact or contact delete to in memory table.

My behaviour has to be When check box checked row has to select automatically and if unchecked row has to un select.

I can use tab, arrow keys and space bar to check and select the rows.

I am using c# win-forms.

So you pretty much just want to select only those rows have the checkbox checked:

            foreach (DataGridViewRow row in dgv.Rows)
            {
                DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
                row.Selected = (bool)cell.Value;
            }

(Obviously,  your checkbox might not be index 1 ).

And you need to set it selected when the user changes the checkbox value, something like

        private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)dgv.CurrentCell;
            dgv.Rows[e.RowIndex].Selected = (bool)cell.EditedFormattedValue;
        }

.

This sort of thing is rather easier in wpf, by the way, you could just bind selected and the checkbox value to the same property.