我的C#技能非常生疏,但基本上我需要关闭一个按钮,我正在以编程方式创建“返回”主菜单。我无法访问我的按钮,我忘记了什么?这是导致问题的一行: ikr1.visible = false;
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 Locker_Rental
{
public partial class Form1 : Form
{
public object ikr1 { get; private set; }
public Form1()
{
InitializeComponent();
button4.Visible = false;
Button lkr1 = new Button();
}
private void button1_Click(object sender, EventArgs e)
{
hide_buttons();
build_LL1_Key_Lockers();
}
private void button2_Click(object sender, EventArgs e)
{
hide_buttons();
build_LL1_Combo_Lockers();
}
private void button3_Click(object sender, EventArgs e)
{
hide_buttons();
build_L2_Combo_Lockers();
}
private void hide_buttons()
{
button1.Visible = false;
button2.Visible = false;
button3.Visible = false;
}
private void show_buttons()
{
button1.Visible = true;
button2.Visible = true;
button3.Visible = true;
}
private void build_LL1_Key_Lockers()
{
button4.Visible = true;
Button lkr1 = new Button();
lkr1.Location = new Point(25, 25);
lkr1.Text = "1";
lkr1.Size = new Size(50, 50);
lkr1.BackColor = System.Drawing.SystemColors.ButtonFace;
Controls.Add(lkr1);
}
private void build_LL1_Combo_Lockers()
{
button4.Visible = true;
}
private void build_L2_Combo_Lockers()
{
button4.Visible = true;
}
private void button4_Click(object sender, EventArgs e)
{
button4.Visible = false;
//turn off ikr1
**ikr1.visible = false;**
show_buttons();
}
}
}
答案 0 :(得分:0)
这是因为您正在引用对象ikr1 ,而不是Button (因为它甚至不存在!)。该按钮在内部方法中实例化,因此您无法从 private void button4_Click 方法进行访问。您需要声明此方法之外的按钮,并在您的事件方法中生成实例。
试试这个:
namespace Locker_Rental
{
public partial class Form1 : Form
{
public object ikr1 { get; private set; }
public Button myButton;
public Form1()
{
InitializeComponent();
button4.Visible = false;
myButton = new Button();
}
private void button1_Click(object sender, EventArgs e)
{
hide_buttons();
build_LL1_Key_Lockers();
}
private void button2_Click(object sender, EventArgs e)
{
hide_buttons();
build_LL1_Combo_Lockers();
}
private void button3_Click(object sender, EventArgs e)
{
hide_buttons();
build_L2_Combo_Lockers();
}
private void hide_buttons()
{
button1.Visible = false;
button2.Visible = false;
button3.Visible = false;
}
private void show_buttons()
{
button1.Visible = true;
button2.Visible = true;
button3.Visible = true;
}
private void build_LL1_Key_Lockers()
{
button4.Visible = true;
myButton = new Button();
myButton.Location = new Point(25, 25);
myButton.Text = "1";
myButton.Size = new Size(50, 50);
myButton.BackColor = System.Drawing.SystemColors.ButtonFace;
Controls.Add(myButton);
}
private void build_LL1_Combo_Lockers()
{
button4.Visible = true;
}
private void build_L2_Combo_Lockers()
{
button4.Visible = true;
}
private void button4_Click(object sender, EventArgs e)
{
button4.Visible = false;
//turn off ikr1
myButton.Visible = false;
show_buttons();
}
}
}