如何更改'对象发送器'

本文关键字:对象 何更改 | 更新日期: 2023-09-27 18:02:35

我在makeDataGridView函数中创建了DataGridView,也许DataGridView右键单击->出现上下文菜单

这是示例代码

public void click(object sender, MouseEventArgs e) {
        if(e.button == MouseButtons.Right) {
               ContextMenuStrip menu = new ContextMenuStrip();
               ToolStripItem insert = menu.Items.Add("insert");
               insert.Click += new EventHandler(context_menu_click);
        }
}
public void context_menu_click(object sender, EventArgs e) {
        / *
           Other event and
           printing .txt file from DataGridView
        */
}

我想打印一个。txt文件从datagridview在'context_menu_click'功能。click函数的sender是DataGridView, context_menu_click函数的sender是ToolStripMenu.

所以,我怎么能打印一个。txt文件从DataGridView在context_menu_click功能?

如何更改'对象发送器'

public void context_menu_click(object sender, EventArgs e)
{
    /*
        Other event and
        printing .txt file from DataGridView
    */
    var item = sender as ToolStripItem  ;
    if (item != null)
    {
        DataGridView gv = item.Tag as DataGridView;
        Console.WriteLine(gv.Name);
    }
}
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        ContextMenuStrip menu = new ContextMenuStrip();
        ToolStripItem insert = menu.Items.Add("insert");
        insert.Tag = sender;
        insert.Click += new EventHandler(context_menu_click);
        menu.Show(this.dataGridView1.PointToScreen(new Point(e.X, e.Y)));
    }
}

您可以将当前的DataGridView添加为Tag到您刚刚创建的ToolStripItem

使用这个来获取点击事件中的DataGridView

((ContextMenuStrip)((ToolStripMenuItem)sender).GetCurrentParent()).SourceControl