【问题标题】:Cant show button text using a contextmenustrip item无法使用上下文菜单项显示按钮文本
【发布时间】:2015-07-28 23:38:24
【问题描述】:

我的表单上有许多由代码生成的按钮(在表单加载事件中),如下所示:

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
}

只有一个名为“查看详细信息”的项目的 ContextMenuStrip,我想要做的是打开一个消息框,当我单击该项目时显示按钮的文本 我有这个:

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

但是当按钮 b 尝试显示 MessageBox 时,我得到 NullReferenceException,请帮助我。

【问题讨论】:

    标签: c# winforms contextmenustrip


    【解决方案1】:

    发件人永远不会是按钮,因为发件人是进行点击的 ToolStripMenuItem。

    尝试检查 SourceControl 属性:

    Control ctrl;
    
    void MyContextMS_Opening(object sender, CancelEventArgs e) {
      ctrl = ((ContextMenuStrip)sender).SourceControl;
    }
    
    private void SeeDetailsToolStripMenuItem_Click(object sender, EventArgs e) {
      Button b = ctrl as Button;
      if (b != null) {
        MessageBox.Show(b.Text);
      }
    }
    

    【讨论】:

    • 如果MyContextMS 处于表单级别,那么您也可以这样做:Button b = (Button)MyContextMS.SourceControl;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    相关资源
    最近更新 更多