user1701826
user1701826

Reputation: 3

Changing the Location of a dynamically created custom control

Let’s say we have the following class Cell, which is composed of a Label control:

class Cell : UserControl
{
    Label base;

    public Cell(Form form)
    {
        base = new Label();
        base.Parent = form;        
        base.Height = 30;
        base.Width = 30;
    }
} 

public partial class Form1 : Form
{ 
    Label label = new Label();

    public Form1()
    {
        InitializeComponent();

        Cell cell = new Cell(this);
        cell.Location = new Point(150, 150);   //this doesnt work            
        label.Location = new Point(150,150);   //but this does
    }
}

A single Cell will display in the Form, but anchored to the top left (0,0) position.

Setting the Location property to a new Point with any other coordinates does nothing, as the Cell will remain in the upper left.

However, if one were to create a new Label and then attempt to set its location, the label would be moved.

Is there a way to do this on my Cell object?

Upvotes: 0

Views: 5308

Answers (2)

RJ Lohan
RJ Lohan

Reputation: 6527

I think your main problem is that you are not adding the controls to a container correctly.

First, you need to add the inner Label to the Cell;

class Cell : UserControl
{       
    Label lbl;

    public Cell()
    {
        lbl = new Label();
        lbl.Parent = form;        
        lbl.Height = 30;
        lbl.Width = 30;
        this.Controls.Add(lbl); // label is now contained by 'Cell'
    }
} 

Then, you need to add the Cell to the Form;

Cell cell = new Cell();
form.Controls.Add(cell);

Also; 'base' is a reserved word, so you can't name the inner label control such.

Upvotes: 2

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34150

try this:

class Cell : Label
    {

    public Cell(Form form)
        {

                this.Parent = form;        
            this.Height = 30;
            this.Width = 30;
        }
    } 


    public partial class Form1 : Form
    { 
        Label label = new Label();


        public Form1()
        {
            InitializeComponent();


            Cell cell = new Cell(this);

            cell.Location = new Point(150, 150);   //this doesnt work

            label.Location = new Point(150,150);   //but this does

        }

Upvotes: 0

Related Questions