Change the location of an object programmatically

134,059

Solution 1

The Location property has type Point which is a struct.

Instead of trying to modify the existing Point, try assigning a new Point object:

 this.balancePanel.Location = new Point(
     this.optionsPanel.Location.X,
     this.balancePanel.Location.Y
 );

Solution 2

Location is a struct. If there aren't any convenience members, you'll need to reassign the entire Location:

this.balancePanel.Location = new Point(
    this.optionsPanel.Location.X,
    this.balancePanel.Location.Y);

Most structs are also immutable, but in the rare (and confusing) case that it is mutable, you can also copy-out, edit, copy-in;

var loc = this.balancePanel.Location;
loc.X = this.optionsPanel.Location.X;
this.balancePanel.Location = loc;

Although I don't recommend the above, since structs should ideally be immutable.

Solution 3

Use either:

balancePanel.Left = optionsPanel.Location.X;

or

balancePanel.Location = new Point(optionsPanel.Location.X, balancePanel.Location.Y);

See the documentation of Location:

Because the Point class is a value type (Structure in Visual Basic, struct in Visual C#), it is returned by value, meaning accessing the property returns a copy of the upper-left point of the control. So, adjusting the X or Y properties of the Point returned from this property will not affect the Left, Right, Top, or Bottom property values of the control. To adjust these properties set each property value individually, or set the Location property with a new Point.

Solution 4

If somehow balancePanel won't work, you could use this:

this.Location = new Point(127, 283);

or

anotherObject.Location = new Point(127, 283);

Solution 5

You need to pass the whole point to location

var point = new Point(50, 100);
this.balancePanel.Location = point;
Share:
134,059
Ahoura Ghotbi
Author by

Ahoura Ghotbi

Updated on July 09, 2022

Comments

  • Ahoura Ghotbi
    Ahoura Ghotbi almost 2 years

    I've tried the following code:

     this.balancePanel.Location.X = this.optionsPanel.Location.X;
    

    to change the location of a panel that I made in design mode while the program is running but it returns an error:

    Cannot modify the return value of 'System.Windows.Forms.Control.Location' because it is not a variable.

    So how can I do it?

  • Mark Byers
    Mark Byers over 12 years
    +1 for mentioning that structs should ideally be immutable. Strangely though... public int X { get; set; } msdn.microsoft.com/en-us/library/system.drawing.point.x.aspx