Can I access controls from another class besides the class they are in?

bigteks

Member
Joined
Nov 7, 2019
Messages
7
I would like to better understand how class structure controls how I can access the objects it contains. Here is some test code. The method called "normal()" can access dataGridView1 but the other two cannot.

C#:
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public void normal(int r)
        {
            DataGridViewRow row = dataGridView1.Rows[r];
        }
        public class inside
        {
            public void nested(int r)
            {
                DataGridViewRow row = dataGridView1.Rows[r];
            }
        }
    }
    public class outside
    {
        public void other(int r)
        {
            DataGridViewRow row = Form1.dataGridView1.Rows[r];
        }
    }

Is there a way for the other two methods to access the datagridview?
 
dataGridView1 is a field declared in Form1. Fully qualified, that would be this.dataGridView1 to indicate a member of the current object. Does it make sense to refer to this.dataGridView1 inside that nested class and expect it to refer to anything? If you expect to refer to an instance field of the Form1 class then you need an instance of the Form1 class to access it on. The fact that the nested class is declared inside Form1 doesn't mean that any instance of either class has any specific connection to any instance of the other.

As for the other class that isn't nested, again, if you want to access an instance member of a type then you need an instance of that type. You can't just use the class and expect to get a control from it. If no instance of that form has been created then no grid has been created either so there's nothing to get. If multiple instances of that form have been created then which grid would you expect to get?

You need to gain an understanding of the difference between types and objects. As a simple example, you don't take dog for a walk but, rather, you take A dog for a walk. Dog is a type of thing but A dog is specific instance of that type of thing. Similarly in your project, Form1 is a type of thing and you need to create instances of that type in order to do anything useful.

Apart from that, you shouldn't be accessing controls outside the form that owns them. It can be done but it is bad practice. Rather, you should add the appropriate properties and/or methods to that form to expose just the functionality required and then the form should do the work. If you want data from a row in a grid then add a method that gets data from a row in a grid. You call that method on the appropriate form instance, it gets the data from the row of the grid and returns it. If you need to be able to make changes to a row in a grid, add a method that takes the data and pushes it into the appropriate row of the appropriate grid.
 
Back
Top Bottom