C# 无法使用contextmenustrip项显示按钮文本
我的表单上有许多按钮是由代码(表单加载事件)生成的,如下所示:C# 无法使用contextmenustrip项显示按钮文本,c#,winforms,contextmenustrip,C#,Winforms,Contextmenustrip,我的表单上有许多按钮是由代码(表单加载事件)生成的,如下所示: 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 t
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
}
但是,当按钮b尝试显示MessageBox时,我在按钮b上看到NullReferenceException,请帮助我。发件人永远不会是按钮,因为发件人是执行单击操作的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代码>。
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);
}
}