0

我正在开发一个 C# winForm 项目,当用户单击我的 dataGridView 的特定行时显示 ContextMenuStrip 它允许用户将数据输入到 toolStripTextBoxItem ...我遇到的问题是当我添加更多控件时通过 TableLayoutPanel 动态到我的 winForm ......这会导致我的 dataGridView 重新定位,但我的 ContextMenuStrip 被“卡在”它以前的位置。如何将 ContextMenuStrip 附加到我的 dataGridView,以便它使用我的 dataGridView 的新位置重新定位自己?

这是我所拥有的一个例子。

ContextMenuStrip ctxtMnuStrp = ContextMenuStrip();
ctxtMnuStrp.Closing += ctxtMnuStrp_Closing;

ToolStripTextBox txtBox = new ToolStripTextBox();

ctxtMnuStrp.Items.Add(txtBox);

DataGridView grid = new DataGridView();
grid.MouseClick += grid_CellClick;

private void grid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    Rectangle rect = grid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
    ctxtMnuStrp.Show(grid.PointToScreen(new Point(rect.Left, rect.Bottom));
 }

 private void ctxtMnuStrp_Closing(object sender, ToolStripDropDownClosingEventArgs e)
 {
     if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked ||
         e.CloseReason == ToolStripDropDownCloseReason.AppFocusChange)
         e.Cancel = true;
 }

就最初定位我的 ContextMenuStrip 并在用户与我的 ContextMenuStrip 交互时保持打开状态而言,这可以正常工作......但是当另一个 dataGridView 添加到我的 winForm 时,它会导致我的网格重新定位并且我的 ContextMenuStrip 不会重新定位/对齐我的网格的新位置并留在它的初始位置。

我该如何解决?

提前致谢,

-DA

4

1 回答 1

0

您需要在处理程序事件函数中使用 sender。像这样的东西:

private void grid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridView source = (DataGridView) sender;
    Rectangle rect = source.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
    ctxtMnuStrp.Show(source.PointToScreen(new Point(rect.Left, rect.Bottom));
}
于 2013-05-09T02:16:27.457 回答