将参数传递给构造函数c#

pass parameters to constructor c#

是否可以将参数传递给 运行 时间生成的事件处理程序?这是创建事件的位置:

private void DataView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            ContextMenuStrip context = new ContextMenuStrip();
            int currentMouseOverRow = DataView.HitTest(e.X, e.Y).RowIndex;
            int row = e.RowIndex;
            int column = e.ColumnIndex;
            if (currentMouseOverRow >= 0)
            {
                int rowsa = e.RowIndex + 1;
                int columnsa = e.ColumnIndex + 1;
                context.Items.Add("Add comment to row: " + rowsa + ", column: " + columnsa);
            }
            context.Show(DataView, new Point(e.RowIndex, e.ColumnIndex));
            context.ItemClicked += new ToolStripItemClickedEventHandler(context_ItemClicked);
        }
    }

我的目标是能够从不可见的 dataGridView1 中获取一个值到用户在主 DataView 上单击的位置的匹配 x 和 y 坐标

public static void context_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {
        Form1 frm = Application.OpenForms.OfType<Form1>().Take(1).FirstOrDefault();
        ToolStripItem item = e.ClickedItem;
        if (item.Text == "Add comment")
        {
            DataTable dt3 = frm.ds1.Tables[0];
            frm.DataView.Rows[x].Cells[y].Value = frm.dataGridView1.Rows[x].Cells[y].Value.ToString();
        }
    }

基本上我需要用索引替换 'x' 和 'y'
非常感谢任何帮助:)

您可以这样做:

private ToolStripItemClickedEventHandler GetHandler(int x, int y)
{
    return (sender, e) => {
        Form1 frm = Application.OpenForms.OfType<Form1>().Take(1).FirstOrDefault();
        ToolStripItem item = e.ClickedItem;
        if (item.Text == "Add comment")
        {
            DataTable dt3 = frm.ds1.Tables[0];
            frm.DataView.Rows[x].Cells[y].Value = frm.dataGridView1.Rows[x].Cells[y].Value.ToString();
        }
    }
}

并使用:

context.ItemClicked += GetHandler(42, 8);

?

或者,您可以在发送者上使用一些状态(通常是 Tag)来保持该状态,然后 sender 中取出它,即

var yourState = (YourState)((Control)sender).Tag;
int x = yourState.X, y = yourState.Y;