//判断是否是右键点击
if (e.Button == MouseButtons.Right)
{
//判断右键点击的位置有没有行.
if (dataGridView1.HitTest(e.X, e.Y).RowIndex != -1)
{
//把之前选中的行都清空.
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
dataGridView1.SelectedRows[i].Selected = false;
}
//把该行给设成选中
dataGridView1.Rows[dataGridView1.HitTest(e.X, e.Y).RowIndex].Selected = true;
//弹出右键菜单.
this.contextMenuStrip1.Show(Control.MousePosition);
}
}