Firas Najar
Firas Najar

Reputation: 1

How To Move A Label To Right?

I want to move a label ( named Label2 ) to the right by pressing a button and when I press the button again I want it to move again ( Hope You Understand )

This is my code:

private void button3_Click(object sender, EventArgs e)
    {
        int x = 28;
        x++;
        label2.Location = new Point(x, 63);
    }

But it doesn't work. What am I doing wrong?

Upvotes: 0

Views: 1963

Answers (3)

Tim S.
Tim S.

Reputation: 56536

This will move it right by 1 pixel each time:

private void button3_Click(object sender, EventArgs e)
    {
        int x = label2.Location.X;
        x++;
        label2.Location = new Point(x, 63);
    }

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109567

This is because you are using a local int x, so it will be reset to 28 each time you click the button.

Move the declaration of x outside the button3_Click() method so that 'x' is a field. Then it will retain its value between each button click.

Obviously you will need to give it a better name; perhaps currentLabelLeft.

Upvotes: 2

Steve Macculan
Steve Macculan

Reputation: 2322

Create two css classes and set them as follows (if you have to set it from code behind):

label2.CssClass = "move_to_right"

Upvotes: 0

Related Questions