gn66
gn66

Reputation: 853

Create several buttons in C# form access them in different form

I have this small piece of code inside a method that is activated when a user press a button in my main form:

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();

Ok, this basically creates a 2/or more buttons in my implementation. The question is, how can I acess this buttons inside the "var bookdp = new Book();" form, because I want that the user be able to click on the new books that appeared.

I'm new to C#.

Thanks for the reply.

Upvotes: 0

Views: 47

Answers (1)

Jeffrey Wieder
Jeffrey Wieder

Reputation: 2376

You need to make those controls public and pass a reference of the owning from into bookdp.

Or if you want to access bookdp's controls from your current form.

        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();

Upvotes: 1

Related Questions