由于 .net 默认操作也会更新slectedrows
你的datagridview
你需要有一个数组来保留旧的选择:
DataGridViewRow[] old;
更新时间为CellMouseDown
(在默认 .net 操作修改您的选择之前):
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
old = new DataGridViewRow[dataGridView1.SelectedRows.Count];
dataGridView1.SelectedRows.CopyTo(old,0);
}
之后,您可以进行更改RowHeaderMouseClick
(as RowHeaderSelect
是默认的datagridviewselectionmode
)或使用CellMouseClick
for FullRowSelect
并重新选择那些旧的选定行:
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
foreach (DataGridViewRow gr in old)
{
if (gr == dataGridView1.CurrentRow)
{
gr.Selected = false;
}
else
{
gr.Selected = true;
}
}
}
编辑:更好的解决方案:
你需要实现你自己的datagridview
从原始派生并覆盖OnCellMouseDown
&OnCellMouseClick
取消默认的取消选择操作并使其平滑。创建一个新类,如下所示:
Using System;
Using System.Windows.Forms;
public class myDataGridView:DataGridView
{
protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e)
{
//base.OnCellMouseDown(e);
this.Rows[e.RowIndex].Selected = !this.Rows[e.RowIndex].Selected;
}
protected override void OnCellMouseClick(DataGridViewCellMouseEventArgs e)
{
//base.OnCellMouseClick(e);
}
}
并在您的 Form.Designer.cs 中进行更改DataGridView
object datagridview1
(如果是这个名字的话)myDataGridView
目的......
例如:改变
private System.Windows.Forms.DataGridView dataGridView1;
to
private myDataGridView dataGridView1;
并改变
this.dataGridView1=new System.Windows.Forms.DataGridView()
to
this.dataGridView1=new myDataGridView ()