How to embed custom control in ToolStrip

ToolStrip is very useful container control, but it has it’s default set of controls you can put onto it. What if you wanted to have, say DateTimePicker, or some totally custom control you have made? You can inherit it from ToolStripItem, override some methods and properties, but there is a much quicker way, if you don’t need any custom behaviour.

To illustrate this i created simple form with ToolStrip, and I embeded DateTimePicker into it, as you can se below (code follows)

As you can see, all the magic that happens is thanks to ToolStripControlHost class.

private void Form1_Load(object sender, EventArgs e)

{

   _deadlineDateTimePicker = new DateTimePicker();

   ToolStripControlHost _deadlineToolStripControlHost = new ToolStripControlHost(_deadlineDateTimePicker);

   _deadlineDateTimePicker.Width = 140;

   _mainToolStrip.SuspendLayout();

   _mainToolStrip.Items.Add(_deadlineToolStripControlHost);

   //add other controls here

   _mainToolStrip.ResumeLayout();

}

Comments

Dizzy says:

Dude this is it! You rock!!!!

facetoface101 says:

Thanks! Great tip! However i have a small problem using the same code i have a menuStrip with dropDown items in the menu and im inserting the DateTimePicker into the menu’s dropDown items. This works and displays but when i open the DateTimePicker and try to scroll to another month etc… it closes But this does not happen when inserted into the top level Menu.

Any Ideas??

kerem celik says:

perfecto

bluto says:

you have saved my time. thanks!