作为.NET默认的动作也将更新slectedrows您的datagridview,你需要有一个数组保留旧的选择:
DataGridViewRow[] old;
Run Code Online (Sandbox Code Playgroud)
将更新CellMouseDown(在默认的.net操作修改您的选择之前):
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
old = new DataGridViewRow[dataGridView1.SelectedRows.Count];
dataGridView1.SelectedRows.CopyTo(old,0);
}
Run Code Online (Sandbox Code Playgroud)
在这之后,你可以做你的变化RowHeaderMouseClick(如RowHeaderSelect为默认的DataGridView selectionmode),或者使用CellMouseClick了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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:更好的解决方案:
您需要实现自己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);
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的Form.Designer.cs中将DataGridView对象datagridview1(如果是名称)更改为myDataGridView对象......
例如:改变
private System.Windows.Forms.DataGridView dataGridView1; 至
private myDataGridView dataGridView1;
Run Code Online (Sandbox Code Playgroud)
并改变
this.dataGridView1=new System.Windows.Forms.DataGridView() 至
this.dataGridView1=new myDataGridView ()
Run Code Online (Sandbox Code Playgroud)