嗨,我正在使用C#进行应用程序.
我想要实现的目标
>我在DataGridView中的结果中选择了多行和CTRL
>然后我右键单击它,它显示选项
>我点击选择所选选项
>所选行保留在DataGridView上,其他行将被删除
我遇到问题的问题
>我用CTRL选择多行
>但是,当我右键单击行时,多个选择消失
注意:我正在使用MouseClick事件右键单击行并生成菜单.该事件的代码如下:
private void SearchPanelDataGridView_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenuStrip smenu = new System.Windows.Forms.ContextMenuStrip();
var htest = SearchPanelDataGridView.HitTest(e.X, e.Y);
SearchPanelDataGridView.ClearSelection();
SearchPanelDataGridView.Rows[htest.RowIndex].Selected = true;
smenu.Items.Add("Clear Record").Name = "Clear Record";
smenu.Items.Add("Pay Amount").Name = "Pay Amount";
smenu.Items.Add("Break Apart").Name = "Break Apart";
smenu.Items.Add("View Details").Name = "View Details";
smenu.Items.Add("Choose Selected").Name = "Choose Selected"; // Choose Rows Option
smenu.Items.Add("Reset").Name = "Reset";
int CurrentMouseOverRow = SearchPanelDataGridView.HitTest(e.X, e.Y).RowIndex;
smenu.Show(SearchPanelDataGridView, new Point(e.X, e.Y));
smenu.ItemClicked += new ToolStripItemClickedEventHandler(smenu_ItemClicked);
}
}
解决方法:
您不需要处理MouseClick事件.只需使用设计器或表单的加载事件创建ContextmenuStrip即可.然后将上下文菜单条分配给DataGridView的ContextMenuStrip属性,然后处理ToolStripMenuItem的Click事件,该事件应删除未选择的行并使用此类代码:
dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(x => !dataGridView1.SelectedRows.Contains(x) && !x.IsNewRow)
.ToList().ForEach(x => dataGridView1.Rows.Remove(x));
这样,将删除所有未选择的行,并且选择将保持不变.