user2040386
user2040386

Reputation: 1

Setting a size for a label border

I made a grid of 9 by 9 labels and each label has a border. After each 3 labels in a row/column I want the border to be thicker then the previous ones. I can't find a way to add this size of that border.

I searched on google, but couldn't find anything useful.

Can anyone help me?

 private void AddNodesToGrid()
{
  pnlGrid.Controls.Clear();
  rooster = new NewLabel[9, 9];
  int Xpos = 0;
  int Ypos = 0;
  for (int I = 0; I < 9; I++)
  {
    for (int T = 0; T < 9; T++)
    {
      rooster[I, T] = new NewLabel(new Node());
      rooster[I, T].Left = Xpos;
      rooster[I, T].Top = Ypos;
      rooster[I, T].Width = 30;
      rooster[I, T].Height = 30;
      rooster[I, T].BorderStyle = BorderStyle.FixedSingle;
      rooster[I, T].TextAlign = ContentAlignment.MiddleCenter;
      pnlGrid.Controls.Add(rooster[I, T]);
      Xpos += 30;
    }
    Xpos = 0;
    Ypos += 30;
  }
}

Upvotes: 0

Views: 6866

Answers (2)

Moha Dehghan
Moha Dehghan

Reputation: 18443

If it were me, I preferred to draw my own table. But if you need to use your labels, I advise you to paint the borders yourslef:

public class NewLabel : Label
{
    //...

    private int _borderWidth = 1;
    public int BorderWidth
    {
        get { return _borderWidth; }
        set
        {
            _borderWidth = value;
            Invalidate();
        }
    }

    private Color _borderColor = Color.Black;
    public Color BorderColor
    {
        get { return _borderColor; }
        set
        {
            _borderColor = value;
            Invalidate();
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        int xy = 0;
        int width = this.ClientSize.Width;
        int height = this.ClientSize.Height;
        Pen pen = new Pen(_borderColor);
        for (int i = 0; i < _borderWidth; i++)
            e.Graphics.DrawRectangle(pen, xy + i, xy + i, width - (i << 1) - 1, height - (i << 1) - 1);
    }
}

Now your NewLabel class has BorderWidth and BorderColor properties that you can set.

(Note: The way I used to draw the border is the fastest one. Creating a pen with required width does not work well because GDI+ puts the center of the line on the specified coordinates.)

Upvotes: 1

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5423

a better way to accomplish this is to use a nested TableLayoutPanel. Create it from the designer and place your labels inside. Steps :

  • Place a 3x3 TableLayoutPanel (Parent Panel).
  • Place a 3x3 TableLayoutPanel (Child Panels) in each cell of the parent panel.
  • set the CellBorderStyle to Single for parent table and child tables.
  • set the Margin for child tables to 0,0,0,0.

You will get this effect :

enter image description here

Upvotes: 0

Related Questions