Dat*_*ase 60 c# select datagridview contextmenu right-click
我的DataGridView中有几列,并且我的行中有数据.我在这里看到了一些解决方案,但我无法将它们结合起来!
只需右键单击一行,它就会选择整行,并显示一个菜单,其中包含删除行的选项,当选择该选项时,它将删除该行.
我做了一些尝试,但没有一个工作,它看起来很乱.我该怎么办?
Dat*_*ase 100
我终于解决了它:
在Visual Studio中,使用名为"DeleteRow"的项创建ContextMenuStrip
然后在DataGridView链接ContextMenuStrip
使用下面的代码帮助我实现了它.
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);
Run Code Online (Sandbox Code Playgroud)
这是很酷的部分
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();
}
Run Code Online (Sandbox Code Playgroud)
pet*_*ria 36
对于这个问题的完整性,最好使用Grid事件而不是鼠标.
首先设置datagrid属性:
SelectionMode到FullRowSelect和RowTemplate/ContextMenuStrip到上下文菜单.
创建CellMouseDown事件: -
private void myDatagridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int rowSelected = e.RowIndex;
if (e.RowIndex != -1)
{
this.myDatagridView.ClearSelection();
this.myDatagridView.Rows[rowSelected].Selected = true;
}
// you now have the selected row with the context menu showing for the user to delete etc.
}
}
Run Code Online (Sandbox Code Playgroud)
小智 9
private void dgvOferty_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
dgvOferty.ClearSelection();
int rowSelected = e.RowIndex;
if (e.RowIndex != -1)
{
this.dgvOferty.Rows[rowSelected].Selected = true;
}
e.ContextMenuStrip = cmstrip;
}
Run Code Online (Sandbox Code Playgroud)
TADA:D.最简单的方式.对于自定义单元格,只需修改一点.
归档时间: |
|
查看次数: |
126162 次 |
最近记录: |