C# buttonの表示・非表示を切り替える

  • 作成日 2021.06.30
  • 更新日 2022.04.06
  • C#
C# buttonの表示・非表示を切り替える

C#で、Visibleを使用して、buttonの表示・非表示を切り替えるサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

Visible使い方

Visibleをtrueにするとbuttonが表示されて、falseにすると非表示となります。

//ボタン表示
button1.Visible = true;

//ボタン非表示
button1.Visible = false;   

サンプルコード

以下は、
「実行」ボタンをクリックすると、buttonの表示・非表示を切り替える
サンプルコードとなります。

using System;
using System.Windows.Forms;

namespace FormTestApp
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();             

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Visible == false) {
                //ボタン表示
                button1.Visible = true; 
            }
            else {
                //ボタン非表示
                button1.Visible = false;       
            }
        }
    }
}

buttonをクリックするごとに表示・非表示が切り替わっていることが確認できます。