Search code examples
c#winformsbuttonflowlayoutpanel

WinForms FlowLayoutPanel alignment problem


When I click on a button in my Floqlayoutpanel they should hide at the place where I clicked on them. But instead they disappear and all the other buttons move.

They should hide at their place

They should hide at their place

But this is what happens

But this is what happens

How I create my Buttons:

 private void CreateButton()
    {
        int buttonIndex = 0;
        for (int i = 0; i < 16; i++)
        {
            Button button = new Button();
            button.Name = $"Button_{buttonIndex}";
            button.Width = 100;
            button.Height = 100;
            button.Click += OnButtonClick;
            button.BackgroundImage = BackSideImage();

            flowLayoutPanel1.Controls.Add(button);

            buttonIndex++;
        }
    }

How I hide my Buttons:

private void CompareCards()
    {
        if (clickedCards.Count >= 3)
        {

                if (clickedCards[0].PairIndex == clickedCards[1].PairIndex)
                {
                    clickedCards[0].Button.Hide();
                    clickedCards[1].Button.Hide();
                }
                else
                {
                   clickedCards[0].Button.BackgroundImage = BackSideImage();
                   clickedCards[1].Button.BackgroundImage = BackSideImage();
                }

                clickedCards.Clear();
        }
    }

Solution

  • Instead of hiding your button, you can make it invisible like this:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            for (int x = 0; x < 9; x++)
            {
                var button = new Button
                {
                    Name = "Test-" + x,
                    Text = "Test-" + x,
                    Width = 100,
                    Height = 100
                };
    
                button.Click += OnButtonClick;
          flowLayoutPanel1.Controls.Add(button);
            }
        }
    
        private void OnButtonClick(object sender, EventArgs e)
        {
            //Instead of this...
            //((Button)sender).Hide();
    
            //Do this...
            var button = ((Button) sender);
            button.FlatStyle = FlatStyle.Flat;
            button.FlatAppearance.BorderColor = BackColor;
            button.FlatAppearance.MouseOverBackColor = BackColor;
            button.FlatAppearance.MouseDownBackColor = BackColor;
            button.Text = string.Empty;
            button.Enabled = false;
        }
    }