Wednesday, September 9, 2009

How to add Button,Checkbox, Radio Button ,any Control to Context Menu in C#


Context Menu is a menu that pops when we click on a control. We can add any windows controls to this context menu using ToolStripControlHost .

There are mainly two ways of doing that. we can either extend the ToolStripControlHost to our class or give the control as a constructor.

Following describe the second method. Say if you have a button called MainButton and context menu should come  when we click that button. and drag and drop contextMenuStrip from the toolbox.

private void MainButton_Click(object sender, EventArgs e)
// Adding a button to Menu
Button B = new Button();
B.Text = "My Button";

// This will bind the event for the button
B.Click += new EventHandler(B_Click);
ToolStripControlHost Ch = new ToolStripControlHost(B);

// Adding a Month Calender
MonthCalendar Mc = new MonthCalendar();
ToolStripControlHost Ch1 = new ToolStripControlHost(Mc);

//Adding a TextBox
TextBox Tb = new TextBox();
Tb.Text = "Add Text";
ToolStripControlHost Ch2 = new ToolStripControlHost(Tb);

//Adding a Check Box
CheckBox Cb = new CheckBox();
Cb.Text = "My Check Box";
ToolStripControlHost Ch3 = new ToolStripControlHost(Cb);

//Adding a Radio Buttion
RadioButton Rb = new RadioButton();
Rb.Text = "My Radio Button";
ToolStripControlHost Ch4 = new ToolStripControlHost(Rb);


contextMenuStrip1.Show(MainButton, 40, 10);
void B_Click(object sender, EventArgs e)
Post a Comment