Cant show button text using a contextmenustrip item

时间:2015-07-28 23:38:25

标签: c# winforms contextmenustrip

I have many buttons on my Form that are generated by code (on form load event) like this:

for(int j = 0; j < 30; j++)
{
    Button btn = new Button();
    btn.Text = numb_cust;
    //The text will be different for every button created
    btn.ContextMenuStrip = MyContextMS;
    //Every button will have this contextMenuStrip
}

And a ContextMenuStrip with only one item called 'See details', and I what I want to do is open a MessageBox showing the text of the button when I click that item I have this:

Button B;
private void MyContextMS_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
    B = sender as Button;
}

private void SeeDetailsToolStripMenuItem_Click(object sender, EventArgs e)
{
    Button b = B;
    MessageBox.Show(b.Text);    
}

But I get NullReferenceException on the Button b when it tries to show the MessageBox, please help me.

1 个答案:

答案 0 :(得分:1)

The sender would never be the button since the sender is the ToolStripMenuItem that is doing the clicking.

Try examining the SourceControl property:

import android.support.v4.app.FragmentActivity;