Share via


How do I use Table layout with ToolStrip?

Here's a super-quick sample of using TableLayout inside of toolstrip. The code below creates a grid of colors, then extends the last "more items" button over the 8 columns.

Note the trick to getting the same methods as the TableLayoutPanel is to cast the LayoutSettings object into a TableLayoutSettings after flipping the LayoutStyle to Table.

toolStrip.LayoutStyle = ToolStripLayoutStyle.Table;
TableLayoutSettings tableLayoutSettings = toolStrip.LayoutSettings as TableLayoutSettings;

You can then use the Dock and Anchor properties to stretch and align the items as you can normal controls in the TableLayoutPanel.

Full sample:

class ColorPickerDropDown : ToolStripDropDown {

public ColorPickerDropDown(IContainer container) {

if (container != null) {
container.Add(this);
}

this.SuspendLayout();
this.LayoutStyle = ToolStripLayoutStyle.Table;
TableLayoutSettings tableLayoutSettings = this.LayoutSettings as TableLayoutSettings;

tableLayoutSettings.ColumnCount = 8;
tableLayoutSettings.RowCount = 8;
Array colors = Enum.GetValues(typeof(System.Drawing.KnownColor));

// Populate an 8x8 grid of colors.
for (int i = 0; i < tableLayoutSettings.ColumnCount; i++) {
for (int j = 0; j < tableLayoutSettings.RowCount; j++) {
Bitmap bmp = new Bitmap(16, 16);
Color c = Color.Empty;
using (Graphics g = Graphics.FromImage(bmp)) {
c = Color.FromKnownColor((KnownColor)colors.GetValue(i*tableLayoutSettings.ColumnCount+j));
g.Clear(c);
g.DrawRectangle(Pens.Black, 0, 0, 15, 15);
}

// create the item, set the text so that the ToolTip shows up showing the full color name.
ToolStripItem item = this.Items.Add(bmp);
item.Text = c.Name;

// switch the DisplayStyle to image
item.DisplayStyle = ToolStripItemDisplayStyle.Image;
item.Tag = c;

}
}

ToolStripItem moreColorsItem = this.Items.Add("More colors...");
moreColorsItem.Click += new EventHandler(moreColorsItem_Click);

tableLayoutSettings.SetCellPosition(moreColorsItem, new TableLayoutPanelCellPosition(0, 8));
tableLayoutSettings.SetColumnSpan(moreColorsItem, 8);

// stretch across the columns
moreColorsItem.Dock = DockStyle.Fill;

// add more vertical space within
moreColorsItem.Padding = new Padding(0, 2, 0, 2);

moreColorsItem.Margin = new Padding(2, 0, 2, 0);

this.ResumeLayout();

}

protected override Padding DefaultPadding {
get {
return new Padding(2);
}
}
void moreColorsItem_Click(object sender, EventArgs e) {
using (ColorDialog cd = new ColorDialog()) {
cd.ShowDialog();
}
}

protected override void OnLayout(LayoutEventArgs e) {
base.OnLayout(e);
}

}