我有一个LayoutPanel
的表单,其中已动态添加buttons
。 buttons
是在运行时添加的,但是我的问题是,如果buttons
为空,我想将属性设置为textBox
之一,并在以后启用它它textBox
不是空的。
这是一个代码示例,我收到的错误如下:
private void Form1_Load(object sender, EventArgs e)
{
// Create 3 buttons
Button button1 = new Button();
button1.Name = "button1";
tableLayoutPanel1.Controls.Add(button1, 0, 0);
Button button2 = new Button();
button1.Name = "button2";
tableLayoutPanel1.Controls.Add(button2, 0, 0);
Button button3 = new Button();
button3.Name = "button1";
tableLayoutPanel1.Controls.Add(button3, 0, 0);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
button1.Enabled = false;
}
else
{
button1.Enabled = true;
}
}
CS0103当前上下文中不存在名称“button1”
我是否应该在其他地方声明按钮,以便整个代码可以看到它们确实存在或在其他地方存在问题?感谢。
答案 0 :(得分:2)
如果要直接从其他方法访问名称按钮,则必须在Form1_Load
之外声明一个按钮,因为在您的情况下按钮仅在Form1_Load
方法中可用:
Button button1;
private void Form1_Load(object sender, EventArgs e)
{
// Create 3 buttons
button1 = new Button();
button1.Name = "button1";
tableLayoutPanel1.Controls.Add(button1, 0, 0);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
button1.Enabled = !string.IsNullOrEmpty(textBox1.Text);
}
或者如果你想在Form1_Load
中声明按钮,你可以像这样访问Button:
private void textBox1_TextChanged(object sender, EventArgs e)
{
var btn = tableLayoutPanel1.Controls.OfType<Button>().Where(x => x.Name == "button1").FirstOrDefault();
(btn as Button).Enabled = !string.IsNullOrEmpty(textBox1.Text);
}
答案 1 :(得分:1)
作为替代方案,您可以从布局面板动态获取控件并设置启用的属性,如下所示:
private void textBox1_TextChanged(object sender, EventArgs e)
{
Control button = tableLayoutPanel1.Controls["button1"];
button.Enabled = string.IsNullOrEmpty(textBox1.Text) ? false : true;
}
这种方法并非安全&#34;在表单级别声明按钮时,我认为在引用控件时需要真正动态的时候提一下是有用的。
答案 2 :(得分:1)
有几种方法可以做到这一点,一种方法是使用TableLayoutPanel的控件集合的Find
方法。
private void textBox1_TextChanged(object sender, EventArgs e)
{
Button btn =(Button)tableLayoutPanel1.Controls.Find("button1", true)[0];
if (string.IsNullOrEmpty(textBox1.Text))
{
btn.Enabled = false;
}
else
{
btn.Enabled = true;
}
}
第二种方法是使用按钮Tag
属性来确定要使用的控件,我过去曾使用它来动态生成控件。
private void Form1_Load(object sender, EventArgs e)
{
// Create 3 buttons
Button button1 = new Button();
button1.Name = "button1";
button1.Tag = 1; //note the Tag property being used
tableLayoutPanel1.Controls.Add(button1, 0, 0);
Button button2 = new Button();
button1.Name = "button2";
button2.Tag = 2;
tableLayoutPanel1.Controls.Add(button2, 0, 0);
Button button3 = new Button();
button3.Name = "button3";
button3.Tag = 3;
tableLayoutPanel1.Controls.Add(button3, 0, 0);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
foreach (Control c in tableLayoutPanel1.Controls) //iterate through controls
{
if ((int)c.Tag == 1) //if Tag is equal then process
{
if (c is Button)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
((Button)c).Enabled = false;
}
else
{
((Button)c).Enabled = true;
}
break; //if you have multiple controls to process remove this
} //and assign the same tag to the controls you want processed
}
}
}