工作中遇到一个场景:在DataGridView上单击鼠标右键弹出快捷菜单,在快捷菜单内需要有“删除本行”、“清空数据”等按钮,于是我就自己实现了一个:
实现步骤如下:
步骤1,建立一个C#下的Windows窗体应用程序,取名DgvMenuStripTest
步骤2,主窗体内的控件只有一个名为dgvTest的DataGridView,对这个DataGridView启用添加、启用编辑、启用删除,并设置其在父容器中停靠
步骤3,为这个DataGridView添加MouseClick事件,代码如下:
/// <summary>
/// DataGridView鼠标单击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgvTest_MouseClick(object sender, MouseEventArgs e)
{
//当前操作的DataGridView
DataGridView dgv = sender as DataGridView;
//当前鼠标位置的行列信息
int col = dgv.HitTest(e.X, e.Y).ColumnIndex;
int row = dgv.HitTest(e.X, e.Y).RowIndex;
//右键弹出菜单
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
//允许用户添加行时,最后一行为未实际添加的行,因此不需考虑弹出菜单
if (row < 0 || (dgv.AllowUserToAddRows && row == dgv.Rows.Count - 1))
{
return;
}
else
{
//取消选中当前所有选中的行和单元格
for (int i = 0; i < dgv.Rows.Count; i++)
{
dgv.Rows[i].Selected = false;
for (int j = 0; j < dgv.Columns.Count; j++)
{
dgv.Rows[i].Cells[j].Selected = false;
}
}
//选中当前鼠标所在的行
dgv.Rows[row].Selected = true;
}
//建立快捷菜单
ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
////功能
//contextMenuStrip.Items.Add("功能1");
//contextMenuStrip.Items.Add("功能2");
//contextMenuStrip.Items.Add("功能3");
////分隔线
//contextMenuStrip.Items.Add(new ToolStripSeparator());
//删除当前行
ToolStripMenuItem tsmiRemoveCurrentRow = new ToolStripMenuItem("删除本行");
tsmiRemoveCurrentRow.Click += (obj, arg) =>
{
dgv.Rows.RemoveAt(row);
};
contextMenuStrip.Items.Add(tsmiRemoveCurrentRow);
//清空所有数据
ToolStripMenuItem tsmiRemoveAll = new ToolStripMenuItem("清空数据");
tsmiRemoveAll.Click += (obj, arg) =>
{
dgv.Rows.Clear();
};
contextMenuStrip.Items.Add(tsmiRemoveAll);
contextMenuStrip.Show(dgv, new Point(e.X, e.Y));
}
}
END
来源:oschina
链接:https://my.oschina.net/u/1425762/blog/513939