Search code examples
c#winformspanel

Navigating through a grid of panels


I'm trying to make a little project in C# using a small grid of panels and four direction buttons as shown here:

enter image description here

But I don't know how to create an easy navigation system using those panels. The "character" is just a colored panel. All the panels are named like their coordinates with a in front of them (p11 to p66) Is there a way to do some kind of function that could take a position of the "character" and color the panel on the same position?

Example

int coords = 21;

private void Up_Click(object sender, EventArgs e)
{
    Move(10);
}

Void Move(int coordchange)
{
    pcoords.BackColor = Color.White;
    coords = coords + coordchange
    pcoords.BackColor = Color.Black;
}

The pcoords part is supposed to be the panel you are currently on. That is the part that I don't know how to make.


Solution

  • public class Panels
    {
         public Panel[, ] PanelsArray=new Panel[6,6] ;
         int xcoordinate;
         int ycoordinate;
         public Panel CurrentPanel{get{return PanelsArray[xcoordinate,ycoordinate];}
         public void MoveUp()
         {
             BeforeMove();
             if(ycoordinate>0) ycoordinate--;
             OnMove();
         }
         //declare MoveDown, MoveLeft and MoveRight similiarly
         ...
         private void BeforeMove()
         {
             CurrentPanel.BackColor=Color.White;
         }
         private void OnMove()
         {
            CurrentPanel.BackColor=Color.Black;
         }
    }
    

    Then in the form class

    public partial class Form1 : Form
    {
        public Panels Panels=new Panels();
        public Form1()
        {
                InitializeComponent();
                Panels.PanelsArray[0,0]=p00;
                PanelsPanelsArray[1,0]=p10;
                Panels.PanelsArray[2,0]=p20;
                //...
                Panels.PanelsArray[5,5]=p55;
    
        }
    ...
    

    You will probably want to add in code to set the starting colours and coordinates.