0

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.

3
  • What do you mean by "Access"? clearly the buttons will be available on the form... Commented Sep 16, 2014 at 18:17
  • I just don't know how to do it :S Like I send the reference as argument to the form, and how can I get a reference from the button? cause I can't just do: "button1 = ..." Commented Sep 16, 2014 at 18:24
  • 1
    Well it could do a search for all the buttons on it. Using a named reference would be very difficult. In general, this proves the case for data-binding and why the winforms architecture doesn't work very well. Commented Sep 16, 2014 at 18:26

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Just one question. I sent the buttonsAdded list to the bookdp form, how can i create an event handler everytime someone presses one of the buttons?
buttonsAdded[0].Click+=new EventHandler(OnButton0Click);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.