954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Trying to access controls on a form from a method

I have a form called MainForm with controls on it say a combobox and textbox.

I have a separate class called routines which hold my methods.
I am simply trying to control the visibility etc of the controls on MainForm by a method in Routines.

The MainForm class is public.

I have tried this on MainForm.

SetUpEntryScreen(this);


in the Routines class
I have a method

Public void static SetUpEntryScreen(MainForm Frm1)
Frm1.

It is here I would expect to be able to access the controls but it doesn't work what am I missing please.

valter
Junior Poster in Training
57 posts since Aug 2007
Reputation Points: 10
Solved Threads: 0
 

Hi,
There are many ways to get the control on a form say Form1 in another method. Based on your need you can use one.
1. You can declare the control definition public, which is private by default or better way would be to create a property with only get method in the form to expose that control. If you need few controls from form this is preferable.
2. You can get all the controls using Form1.Controls property. This will return collection of all the control in form. And you can loop throw it and identify the control using name property of control.

DangerDev
Posting Pro in Training
485 posts since Jan 2008
Reputation Points: 165
Solved Threads: 59
 

Thank you Danger,
Since I will have a lot of controls to change I though a for each loop with a switch might be the way to go.

I have tried this on the MainForm to call the method

Routines.SetUpEntryForm(this);

In the Routines class
public static void SetUpEntryForm(MainForm Frm1)
{
foreach (Control Ctl in MainForm.Controls)
{
switch (Ctl.Name)
{
case CmbRecords:
Ctl.Items.Clear();
Ctl.Visible = false;
Ctl.Text = null;
break;

It's obviously not right as Intellisense does not give me the Control names. Your further help will be welcome.

valter
Junior Poster in Training
57 posts since Aug 2007
Reputation Points: 10
Solved Threads: 0
 

Please use code tags if you post code.
I think foreach (Control Ctl in MainForm.Controls) should read foreach (Control Ctl in Frm1.Controls), also CmbRecords should resolve to a string.

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You