右键单击以选中一个DataGridView一行,并显示一个菜单来删除它 [英] Right click to select a row in a Datagridview and show a menu to delete it

查看:571
本文介绍了右键单击以选中一个DataGridView一行,并显示一个菜单来删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的DataGridView几列,且有数据在我行。我看到这里几个解决方案,但我不能将它们组合起来!

I have few columns in my DataGridView, and there is data in my rows. I saw few solutions in here, but I can not combine them!

简单的方式来某行右键点击,它会选择整行,并显示一个菜单选项删除行,当选项选中它会删除行。

Simply a way to right-click on a row, it will select the whole row and show a menu with an option to delete the row and when the option selected it will delete the row.

我做了一些尝试,但没有工作,它看起来凌乱。我应该怎么办?

I made few attempts but none is working and it looks messy. What should I do?

推荐答案

我终于解决了它:


  • 在Visual Studio中,创建一个使用的ContextMenuStrip被称为DeleteRow的项目

  • In Visual Studio, create a ContextMenuStrip with an item called "DeleteRow"

然后在DataGridView的链接的ContextMenuStrip

Then at the DataGridView link the ContextMenuStrip

使用code下面帮我得到它的工作。

Using the code below helped me getting it work.

this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);

下面是最酷的部分。

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        var hti = MyDataGridView.HitTest(e.X, e.Y);
        MyDataGridView.ClearSelection();
        MyDataGridView.Rows[hti.RowIndex].Selected = true;
    }
}

private void DeleteRow_Click(object sender, EventArgs e)
{
    Int32 rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
    MyDataGridView.Rows.RemoveAt(rowToDelete);
    MyDataGridView.ClearSelection();
}

我希望code可以帮助别人: - )

I hope the code will help others :-)

我欢迎任何修正,如果有一个错误。

I welcome any correction if there is an error.

这篇关于右键单击以选中一个DataGridView一行,并显示一个菜单来删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆