tags:

views:

531

answers:

2

Is there any way in WinForms to emulate border-collapse from CSS?

Imagine this: You have a Panel control with a border of FixedSingle, giving it a 1px black border, docked to the top of a form. You add a second Panel control with the same border and also docked to the top, in effect stacking that Panel underneath the first Panel. The problem is, where the bottom of the top Panel touches the top of the bottom Panel, the border is now 2px wide (bottom of top Panel (1px) + top of bottom Panel (1px) = 2px).

I have been messing with the Panel control properties, but I couldn't see anything to have these touching edges overlap so there is only 1px of border between the Panels. Anyone have any ideas?

(I am using Visual Basic .NET 2008)

A: 

Like most built-in controls, the Panel's border property is an all-or-nothing kind of property. It would be convenient to specify which sides of a Panel get borders, but alas no. If your purpose is to create a grid-style view with few cells, you might be better off drawing the data (and the associated grid lines) into a single Panel yourself.

Jim H.
+1  A: 

Just create your own panel derived control. Fake the border by drawing it the way you want it. For example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class MyPanel : Panel {
  public MyPanel() {
    this.Dock = DockStyle.Top;
    this.DoubleBuffered = true;
    this.SetStyle(ControlStyles.ResizeRedraw, true);
  }
  protected override void OnPaintBackground(PaintEventArgs e) {
    base.OnPaintBackground(e);
    int y = this.ClientSize.Height - 1;
    int x = this.ClientSize.Width-1;
    e.Graphics.DrawLine(Pens.Black, 0, 0, 0, y);
    e.Graphics.DrawLine(Pens.Black, 0, y, x, y);
    e.Graphics.DrawLine(Pens.Black, x, 0, x, y);
  }
}

Add a new class to your project and paste the code show above. Compile. Drop the new control from the top of your toolbox onto your form.

Hans Passant
I'm going to try this out Monday. Thanks!
HardCode