我在方法中有一小段代码,当用户按下主窗体中的按钮时,该方法会被激活:
int tmp = 0;
int j = 20;
var bookdp = new Book(); // DIFFERENT FORM
while(books.Count > tmp)
{
bookdp.Controls.Add(new Button()
{
Text = "" + this.books[tmp],
Size = new System.Drawing.Size(200, 75),
Location = new System.Drawing.Point (20, j),
TextAlign = ContentAlignment.MiddleLeft,
Name = "" + button1 + tmp
});
tmp++;
j += 80;
}
bookdp.Show();
this.Hide();
好的,这基本上会在我的实现中创建一个2个或更多按钮。问题是,如何在“var bookdp = new Book();”中访问这些按钮。表单,因为我希望用户能够点击出现的新书。
我是C#的新手。
感谢您的回复。
答案 0 :(得分:1)
您需要公开这些控件并将拥有的引用传递给bookdp。
或者,如果您想从当前表单访问bookdp的控件。
int tmp = 0;
int j = 20;
var bookdp = new Book(); // DIFFERENT FORM
List<Button> buttonsAdded = new List<Button>(books.Count);
while (books.Count > tmp)
{
Button newButton = new Button()
{
Text = "" + this.books[tmp],
Size = new System.Drawing.Size(200, 75),
Location = new System.Drawing.Point(20, j),
TextAlign = ContentAlignment.MiddleLeft,
Name = "" + button1 + tmp
};
bookdp.Controls.Add(newButton);
buttonsAdded.Add(buttonsAdded);
tmp++;
j += 80;
}
bookdp.Show();
string text = buttonsAdded[0].Text;
this.Hide();