简体   繁体   中英

How to change the 'object sender'?

I create DataGridView in makeDataGridView function, and maybe datagridview rightclick -> appear context menu

This is sample code

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
        */
}

I want to print a .txt file from datagridview in 'context_menu_click' function. The sender of click function is DataGridView, but context_menu_click sender is ToolStripMenu.

So, How can I print a .txt file from DataGridView in context_menu_click function?

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)));
    }
}

You can add current DataGridView as Tag to the ToolStripItem you just create

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM