Tried GetCurrentParent()
and failed and read all other answers.
I am working on a project where user may click on button and generate new controls, so I have to generate them on run time.
When I created a contextmenustrip
and added the following items
----------------------
Show
----------------------
Style -> change Color
----------------------
Both items should access richtextbox
. The show click works properly but "change color" does not.
The problem occurs when I try to get the richtextbox
in where the menu popped from.Show
successfully access the richtextbox
but changecolor
does not.
Here is my code
public static System.Windows.Forms.RichTextBox Create_rich_text_box()
{
System.Windows.Forms.RichTextBox r = new System.Windows.Forms.RichTextBox();
r.ContextMenuStrip = Create_new_context_menu_strip();
return r;
}
private static System.Windows.Forms.ContextMenuStrip Create_new_context_menu_strip()
{
//contextmenu
System.Windows.Forms.ContextMenuStrip ctx = new System.Windows.Forms.ContextMenuStrip();
//display contents
var show = new System.Windows.Forms.ToolStripMenuItem("show");
show.Click += _show_click;
//change color
var style = new System.Windows.Forms.ToolStripMenuItem("Style");
var changecolor = new System.Windows.Forms.ToolStripMenuItem("change color");
changecolor.Click += _chnge_color_click;
style.DropDownItems.Add(changecolor);
ctx.Items.Add(show);
ctx.Items.Add(style);
ctx.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
});
return ctx;
}
private static System.Windows.Forms.RichTextBox get_current_rtx(object sender)
{
try
{
System.Windows.Forms.ToolStripMenuItem tsm = sender as System.Windows.Forms.ToolStripMenuItem;
var par = tsm.GetCurrentParent();
var ctx = (par as System.Windows.Forms.ContextMenuStrip);
return ctx.SourceControl as System.Windows.Forms.RichTextBox;
}
catch { }
return null;
}
private static void _chnge_color_click(object sender, EventArgs e)
{
System.Windows.Forms.RichTextBox r = get_current_rtx(sender);
r.BackColor = System.Drawing.Color.Gray;
System.Windows.Forms.MessageBox.Show("Success");
}
private static void _show_click(object sender, EventArgs e)
{
try
{
System.Windows.Forms.RichTextBox r = get_current_rtx(sender);
System.Windows.Forms.MessageBox.Show(r.Text);
}
catch
{
System.Windows.Forms.MessageBox.Show("This will fail");
}
}