C# 如何获取打开ContextMenuStrip的控件?
我正在寻找一种方法,为程序提供导致ContextMenuStrip打开的控件。我为多个组合框分配相同的条带以重用它们,就像在课程开始时这样C# 如何获取打开ContextMenuStrip的控件?,c#,combobox,contextmenustrip,C#,Combobox,Contextmenustrip,我正在寻找一种方法,为程序提供导致ContextMenuStrip打开的控件。我为多个组合框分配相同的条带以重用它们,就像在课程开始时这样 myComboBox.ContextMenuStrip = changevaluestrip; 这里我有“添加值”和“删除值”,当然,每一个都必须知道它必须从哪个组合框中删除值。我试着和你一起做 private void removeValueToolStrip_Click(object sender, EventArgs e) { ToolStr
myComboBox.ContextMenuStrip = changevaluestrip;
这里我有“添加值”和“删除值”,当然,每一个都必须知道它必须从哪个组合框中删除值。我试着和你一起做
private void removeValueToolStrip_Click(object sender, EventArgs e)
{
ToolStripMenuItem usedbox = sender as ToolStripMenuItem;
var parent = usedbox.GetCurrentParent();
DialogResult res = MessageBox.Show("Do you really want to delete this value?", "Delete Value", MessageBoxButtons.YesNo);
if (res == DialogResult.Yes)
{
//Delete it from the combobox it was sent from
}
}
但这并没有真正起作用,只是给了我作为发送者的“删除值”…也许是你想要的。是的,@KingKing是对的。为此,您需要使用
ContextMenuStrip.SourceControl
。
这里有一个片段可以帮你做到这一点
ToolStripMenuItem usedbox = sender as ToolStripMenuItem;
ContextMenuStrip parent = usedbox.GetCurrentParent() as ContextMenuStrip;
if (parent != null)
{
ComboBox combo = parent.SourceControl as ComboBox;
if (combo != null)
{
//use combobox here
}
}