0

I am trying to set the location of the control after some event based on the location of EventArg pictureBox1.Location.X = e.X;.

However this does not work it Cannot Modify expression because it is not a variable. But i was under the impression that x coordinate is a property and can be set. What is going on here ?

Win Coder
  • 6,628
  • 11
  • 54
  • 81

3 Answers3

3

Try this instead:

pictureBox1.Location = new Point(e.X, pictureBox.Location.Y);

or if you don't want to construct a new variable:

Point location = pictureBox1.Location;
location.X = e.X;
pictureBox1.Location = location;

This is because Point is a value type, and therefore you can't just edit one of its values, as it won't propagate. Its value is stored, not a reference to the value. You can't just edit it, you need to build the object again. This could compile, but it would do absolutely nothing, in no possible scenario, so the compiler makes sure you don't do this error.

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
3

Because System.Drawing.Point is a value type, when you call pictureBox1.Location, you are actually getting a copy of the Point. A whole new object is constructed and filled with the fields of pictureBox1.Location.

As such, the compiler is trying to protect you from doing something silly, as changing the value of the copy would not propagate to the value of Location.

As such, and as mentioned in the other answers, you should construct a new Point and assign it to the Location property.

Rotem
  • 21,452
  • 6
  • 62
  • 109
2

Some people here talk about Point is a value type and you can't change its X and Y, that kind of explanation can confuse you much. I post this answer here to help you understand why you can't change it's Location. That's because Location is a Property which returns a Structure not a reference to an Object, if you have a field instead, you can change that way, like this:

public class YourControl : BaseControl {
   public Point Location;
}
//Then you can change the Location your way:
yourControl.Location.X = ....

However, as I said, Location is a Property which returns a copy of a value type (structure), like this:

public class YourControl : BaseControl {
    private Point location;
    public Point Location {
        get {
           return location;//a copy
        }
        set {
           location = value;
        } 
    }
}
//So when you call this:
yourControl.Location
//you will get a copy of your Location, and any changes made on this copy won't affect
//the actual structure, the compiler needs to prevent doing so.
yourControl.Location.X = ... //Should not be executed...

This is not the only case for Location, you can find this issue in all other Properties which are value types.

King King
  • 61,710
  • 16
  • 105
  • 130