按钮是应用程序,软件或网页的重要组成部分。它允许用户与应用程序或软件进行交互。在Button中,允许您设置一个值,该值代表该按钮,并使用Visible属性显示其子按钮。它由Button类提供。
如果要显示给定的按钮及其子控件,则将Visible属性的值设置为true,否则设置为false。此属性的默认值为true。您可以通过两种不同的方法使用此属性:
1.设计时:这是设置按钮可见性的最简单方法。使用以下步骤:
- 第1步:创建一个Windows窗体,如下图所示:
Visual Studio->文件->新建->项目-> WindowsFormApp - 步骤2:从工具箱中拖动Button控件,并将其放在Windows窗体上。您可以根据需要在Windows窗体上的任意位置放置一个Button控件。
- 步骤3:拖放之后,您将转到Button控件的属性来设置Button的Visible属性。
输出:
2.运行时:比上述方法有些棘手。在此方法中,可以借助给定的语法以编程方式设置Button的Visible属性:
public bool Visible { get; set; }
在此,此属性的返回类型为System.Boolean 。以下步骤用于设置Button的Visible属性:
- 步骤1:使用Button类提供的Button()构造函数创建一个按钮。
// Creating Button using Button class Button MyButton = new Button();
- 步骤2:创建Button之后,设置Button类提供的Button的Visible属性。
// Set the visibility of the button MyButton.Visible = true;
- 步骤3:最后使用Add()方法将此按钮控件添加到中。
// Add this Button to form this.Controls.Add(Mybutton);
例子:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Visible = true; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button // This button in not visible in the output because the // visibility of this button is set to be false Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Visible = false; // Adding this button to form this.Controls.Add(Mybutton1); } } }
输出:
在将“取消”按钮的可见性设置为false之前,输出是这样的:将取消按钮的可见性设置为false后,输出如下所示: