Introduction
This article aims to show the use of ToolBox control which can be useful for projects like IDE development and other design surface projects.
Background
The design cue has been borrowed from Visual Studio 2010 and have made all possible efforts to keep it simple and usable.
Using the code
Download the attached assembly and add a reference in your project to pplStuff.Controls.ToolBox.dll.
Create an instance of the ToolBox
private void Form1_Load(object sender, EventArgs e)
{
ToolBox toolBox = new ToolBox();
}
Add Groups
You may create individual groups and add it to the toolbox
ToolGroup grpCommon = new ToolGroup();
grpCommon.Caption = "Common Control";
grpCommon.Collapsed = false;
toolBox.ToolGroups.Add(grpCommon);
Or create them using constructor
toolBox.ToolGroups.Add(new ToolGroup("Common Control", false));
Add Items to Groups
toolBox.ToolItems.Add(new ToolItem(toolBox.ToolGroups[0], "Pointer", Image.FromFile(@"C:\Images\Pointer.jpg"), new object()));
The first parameter of the ToolItem constructor takes a ToolGroup object which must be already added to the control. Second parameter defines the text displayed on the item. Next is the image to be used when creating the toolitem.
The last parameter is an user defined object which can be accessed during runtime. This has been added to cater to requirements when associating an object to an item becomes necessary.
Events
The toolbox provides one event for Selection Change of items and provides access to the currently selected ToolItem.
toolBox.SelectionChanged += new EventHandler(toolBox1_SelectionChanged);
void toolBox_SelectionChanged(object sender, EventArgs e)
{
ToolItem item = sender as ToolItem;
MessageBox.Show(item.Text);
}
Clearing item selection
ClearItemSections() method can be used to clear current selection of item in the toolbox.
toolBox.ClearItemSections();
Removing Groups/Items from the ToolBox
Groups or items can be removed from the toolbox by simply removing them from the collections
To remove the first group
toolBox.ToolGroups.Remove(toolBox.ToolGroups[0]);
To remove the 5th item from the toolbox (Item indexes are independent of the group they are in)
toolBox.ToolItems.Remove(toolBox.ToolItems[4]);
Drag & Drop
The toolbox supports DragDrop operation and can be implemented as follows
- I have created a panel and placed a label inside the panel to show the text of item being dropped.
private void panel1_DragEnter(object sender, DragEventArgs e)
{
if (e.AllowedEffect == DragDropEffects.Copy)
e.Effect = DragDropEffects.Copy;
}
private void panel1_DragDrop(object sender, DragEventArgs e)
{
ToolItem item = e.Data.GetData(typeof(ToolItem)) as ToolItem;
lblDemo.Text = item.Text;
}