问题描述
我的 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.
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 中,使用名为DeleteRow"的项目创建一个 ContextMenuStrip
In Visual Studio, create a ContextMenuStrip with an item called "DeleteRow"
然后在 DataGridView 链接 ContextMenuStrip
Then at the DataGridView link the ContextMenuStrip
使用下面的代码帮助我让它工作.
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();
}
这篇关于右键单击以在 Datagridview 中选择一行并显示一个菜单以将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!