Majid
Majid

Reputation: 101

Interchange positions of two buttons

I want to replace button location (Interchange location )by black button when i click it and it is next to black button (b9=black button and lable1 is a temp for saving location).

I made this method :

void checkLocation()
    {
        if (ActiveControl.Location == new Point(5, 7))//-----------for button 1
        {
            if (b9.Location == new Point(83, 7) || b9.Location == new Point(5, 71))
            {
                label1.Location = ActiveControl.Location;
                ActiveControl.Location = b9.Location;
                b9.Location = label1.Location;
            }
        }// it continue for every button

and I write this code for every button_click

private void button1_Click(object sender, EventArgs e)
    {
       checkLocation();
    }

now,some button don't work currently . what is wrong ?

Upvotes: 0

Views: 1118

Answers (2)

Majid
Majid

Reputation: 101

by thanks from p.s.w.g I think it is shorter and fit :

void swapLocation()
    {
        var tmp = ActiveControl.Location;

        if((ActiveControl.Location.X==b9.Location.X)&&(Math.Abs(b9.Location.Y-ActiveControl.Location.Y)<=60))
            {
             ActiveControl.Location = b9.Location;
             b9.Location = tmp;
            }
        if ((ActiveControl.Location.Y == b9.Location.Y) && (Math.Abs(b9.Location.X-ActiveControl.Location.X) <= 70))
            {
            ActiveControl.Location = b9.Location;
            b9.Location = tmp;
            }
        }

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149098

Just do this to swap the locations of two controls:

void swapLocation()
{
    var tmp = ActiveControl.Location;
    ActiveControl.Location = b9.Location;
    b9.Location = tmp;
}

Or more generally

void swapLocation(Control x, Control y)
{
    var tmp = x.Location;
    x.Location = y.Location;
    y.Location = tmp;
}

...
swapLocation(ActiveControl, b9);

Update

It looks like you're trying to implement a version of the 15-puzzle. There are numerous ways to solve this, but to avoid a radical rewrite of your program I'd recommend this:

private int buttonWidth = 82;
private int buttonHeight = 82; // adjust these values as needed

private void button_Click(object sender, EventArgs e)
{
   if ((Math.Abs(ActiveControl.Location.X - b9.Location.X) == 0 &&
        Math.Abs(ActiveControl.Location.Y - b9.Location.Y) == buttonHeight) ||
       (Math.Abs(ActiveControl.Location.X - b9.Location.X) == buttonWidth &&
        Math.Abs(ActiveControl.Location.Y - b9.Location.Y) == 0))
   {
       swapLocation(ActiveControl, b9);
   }
}

This basically checks to see if the ActiveControl is either directly above, below, to the left, or the right of b9, and if it is, swaps them. You can use this click handler for all buttons 1 through 8. Note this method only works with the buttons are a fixed width and height.

Upvotes: 0

Related Questions