c# Winform:如何在数据网格按钮下方显示上下文菜单



我有一个网格和一个列类型是按钮列。我想,当用户点击按钮,然后菜单应该显示在按钮下方,但我不能做到这一点。dgList是datagridview的名称。如果没有空间显示菜单,则菜单位置将动态调整。

这是我的代码,我尝试

private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Salary", typeof(int));
DataRow dr = null;
dr = dt.NewRow();
dr[0] = 1;
dr[1] = "Joydip";
dr[2] = 5200;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 2;
dr[1] = "Salim";
dr[2] = 3200;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 3;
dr[1] = "Sukumar";
dr[2] = 6000;
dt.Rows.Add(dr);
dgList.AutoGenerateColumns = false;
dgList.DataSource = dt;
dgList.Columns[0].DataPropertyName = "ID";
dgList.Columns[1].DataPropertyName = "Name";
dgList.Columns[2].DataPropertyName = "Salary";
}
private void dgList_MouseClick(object sender, MouseEventArgs e)
{
int currentMouseOverRow = dgList.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0)
contextMenuStrip1.Show(dgList, new Point(e.X, e.Y));

}

我也试过这个代码,但没有运气。

private void dgList_MouseClick(object sender, MouseEventArgs e)
{
DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
if (currentCell != null)
{
ContextMenuStrip cms = currentCell.ContextMenuStrip;
Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
Point p = new Point(r.X + r.Width, r.Y + r.Height);
contextMenuStrip1.Show(currentCell.DataGridView, p);
}
}

请指导我在我的代码中有什么错误。如何实现我所寻找的。

感谢

问题已修复。这里的工作代码

private void dgList_MouseClick(object sender, MouseEventArgs e)
{
DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
if (currentCell != null && currentCell.ColumnIndex==3)
{
ContextMenuStrip cms = currentCell.ContextMenuStrip;
Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
Point p = new Point(r.X, r.Y + r.Height);
contextMenuStrip1.Show(currentCell.DataGridView, p);
}
}

相关内容

  • 没有找到相关文章

最新更新