我创建了一个动态表单,并在其中创建了动态对象。但是,由于某种原因,当我创建动态事件处理程序时,事件处理程序不会获取动态对象。也就是说,它们不会出现在Visual中的下拉选项列表中。
守则:
private void btnShop_Click(object sender, EventArgs e)
{
Form frmShop = new Form();
frmShop.Show();
Button newButton = new Button();
Button Add = new Button();
Label Meat = new Label();
Label Carrots = new Label();
Label DogFood = new Label();
Label Fish = new Label();
Label Rainbows = new Label();
frmShop.Controls.Add(Meat);
frmShop.Controls.Add(Carrots);
frmShop.Controls.Add(DogFood);
frmShop.Controls.Add(Fish);
frmShop.Controls.Add(Rainbows);
frmShop.Controls.Add(newButton);
frmShop.Controls.Add(Add);
frmShop.Size = new Size(300,300);
//HERE IS MY PROBLEM v //
frmShop.Controls.Add(lblCount)
}发布于 2018-04-28 14:54:29
变量彩虹是btnShop_Click事件处理程序的本地变量,即使使用相同的名称,也不能在其他方法中使用该变量。在这里了解范围界定
您需要将控件移动到全局范围,或给它们命名并从窗体控件集合中检索它们。
例如,将接收动态表单的变量移动到全局范围(在任何类方法之外,但在类声明中)。
private Form frmShop = null;
private void btnShop_Click(object sender, EventArgs e)
{
frmShow = new Form();
.....
// Set the Name property for the label
Label Rainbow = new Label { Name = "Rainbow" }
...
frmShow.Controls.Add(Rainbow);
}
protected void newButton_Click(object sender, EventArgs e)
{
...
// Try to extract the label required from the form controls collection
// using the specified name
Label aRainbowLabel = frmShow.Controls
.OfType<Label>()
.FirstOrDefault(x=>x.Name=="Rainbow");
aRainbowLabel.Text = "Rainbows: 1";
} 小心,你走的是一条危险的道路。变量frmShow是全局的,如果再次单击相同的按钮,您将创建第二个具有相同元素的表单。如果这是正常的,那么没有问题,但是如果您只想要这种类型的一种形式,则需要在创建表单之前检查变量是否为null,如果关闭该表单,则需要将变量frmShow设置为null。
https://stackoverflow.com/questions/50077678
复制相似问题