【发布时间】:2021-08-10 18:01:18
【问题描述】:
作为我的作业要求,我必须在创建表单后立即创建与存储在 ProductManager 中的数组中的产品数量一样多的按钮。按下按钮时,将打开另一个表单,显示产品的属性并允许将其添加到购物篮中。但是,由于这些按钮是最初创建的,因此我无法在它们的事件中按照我的意愿行事。比如我需要获取点击的按钮对应的是哪个产品,我需要以另一种形式展示这个产品的特性。这里出现了两个不同的问题:
1- 创建按钮后,我只需要使用它们的 Click 事件,但我无法访问它。
2- 我无法控制在显示产品详细信息的表单中单击按钮的产品。
加载表单时按钮自动出现的表单: click here to see what it seems like
private void Form2_Load(object sender, EventArgs e)
{
int buttonId = 0;
int locationX = 2;
int locationY = 2;
for (int i = 0; i < productManager.getAll().Count; i++)
{
Button newButton = new Button();
newButton.Image = Image.FromFile(productManager.getAll()[i].Path);
newButton.Text =locationX.ToString();
newButton.Size= new Size(180, 180);
newButton.Location = new Point(locationX,locationY);
locationX += 200;
if (locationX > 805)
{
locationY += 200;
locationX = 2;
}
this.Controls.Add(newButton);
currentProduct = productManager.getAll()[i];
newButton.Click += new EventHandler(button_Click);
}
}
我尝试使用的两个主题函数(事件):
private void CurrentButton_Click(object sender, EventArgs e)
{
productDetailsWindow.Show();
}
protected void button_Click(object sender, EventArgs e)
{
Product product = sender as Product;
productDetailsWindow.Show();
}
包含产品属性和添加到购物车按钮click here to see what it seems like的表单
【问题讨论】:
标签: c# forms winforms object events