0
votes

I have an application that consists of several forms. There is a MainForm and then other forms open up within this MainForm. One of the child forms that opens up (we'll just call it Form1) contains a user control that has controls inside it, such as a datagrid view. This datagridview control has several events that are triggered, one being a "cellclick" event.

This click event must access a public timer object that is declared in Form1.

Currently just to make it work I used the code:

((Form1)this.Parent.Parent.Parent.Parent.Parent).clickTimer.Start();

However this doesn't seem like the best way I could be accessing this Timer object, and could potentially be a headache for future development of Form1 and its User Controls.

What are alternative ways of accessing my Form1 timer from inside the user control's datagridview click event?

Any advice is appreciated as I'm drawing a blank on this right now.

Thanks

3
I suspect the design; I'd strive to make child controls independent of their parents.Emond

3 Answers

2
votes

You could have the user control take the Timer instance as constructor argument and store it in a private backing field for future access.

0
votes

Well I figured out more elegant way to access my Form1 object(as opposed to use Parent.Parent.Parent...etc.) with:

Control activeForm = this.FindForm();

So now I have:

((Form1)activeForm).clickTimer.Start();

The above code gives me the form the userControl exists inside(Form1), and since the Forms that the UC exists inside will always have a Timer, this should work even if the user control is placed on a different form (say Form2).

However, @Darin did provide a good alternative, but I chose to use my solution because it provided me the quickest way to fix my issue with least amount of code changes required yet still provides low maintainability for my Forms. Specific to my situation, of course.

0
votes

You could create a static event in the child form and register to it in the parent form.

Trigger the event on "cellclick" and trigger the timer in the event handler on your parent form.