ok i'm working in visual studio.

im working on an application with multiple forms, and im trying to access controls in form1, from the form2 class. Heres what im using now:

public partial class Form2 : Form
{
    private Button btn1;

    public Form2(Button _btn1)
    {
        InitializeComponent();

        btn1 = _btn1;
    }

    public void SomeEvent()
    {
        btn1.Text = "";
    }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void SomeEvent()
    {
        Form2 newform = new Form2(button1);
        newform.Show();
    }
}

just an example.

i was wondering if there was another way to do this (if i wanted to pass more than one controls) rather than passing each control like the one above?

Pass a Control[] array in the constructor. Or you can make a struct so you can assign controls to the struct and pass the struct -- that way you don't have 90 parameters :)

You should leave a parameterless constructor for your form in place. Visual Studio's designer requires a ctor with no parameters to generate a control except for the top level control being designer. For example set your ctors up this way:

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmFile : Form
  {
    object _o;
    public frmFile()
    {
      InitializeComponent();
    }
    public frmFile(object o)
      : this()
    {
      this._o = o;
    }

Sure, if that is what you really want to do:

public Form2(Control [] controls) {}
//or
    public Form2(Button btn1, Button btn2, Button btn3)// etc.
    {}

Sure, if that is what you really want to do:

public Form2(Control [] controls) {}
//or
    public Form2(Button btn1, Button btn2, Button btn3)// etc.
    {}

or, you could even pass in reference to other form if the called form will know the controls and they are accessible:

public Form2(Form form1) {}
commented: That's how I would have done it! +3
commented: Passing a Form to a Form, nice! +12
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.