Results 1 to 21 of 21

Thread: [RESOLVED] accessing variables and controls in the startup form from other forms

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Resolved [RESOLVED] accessing variables and controls in the startup form from other forms

    When the Form1 gets instantiated at startup, what is its name? How do i access variables in in the startup form from other forms?
    Last edited by Muddy; Aug 8th, 2006 at 01:07 PM. Reason: RESOLVED

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: accessing variables in the startup form from other forms

    You access members of a form the same way you access members of any other object. You need a reference to the object and then you specify the member you want access. Given the you're talking about the startup form, i.e. the first object created, then it si going to have to provide a reference to itself to other objects when it creates them. You can't just pluck a reference to an object out of thin air. I'd suggest that you read the "Forms in VB.NET" tutorial in my signature. The principles are exactly the same in C# and you can use one of the code converters in my signature if you need to convert the code samples.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Re: accessing variables in the startup form from other forms

    Thanks,

    I had thought of that, but when I try to pass the object "this" which is the startup form I get the error

    "Error 1 Cannot pass '<this>' as a ref or out argument because it is read-only"

    offending line of code (snippet of the line) is:

    new BasicControl(ref this)

  4. #4
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: accessing variables in the startup form from other forms

    remove the "ref"
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  5. #5
    Hyperactive Member drattansingh's Avatar
    Join Date
    Sep 2005
    Posts
    395

    Re: accessing variables in the startup form from other forms

    ok. Take Form1, and Form2. Form1 is our main form whlie Form2 is like the child form.

    Here is Form2 constructor:


    Form1 Main; // object declared for reference of Form1.
    public Form2(Form1 FM)
    {
    Main = FM; // this line instantates the reference of Form1. Thus whenever you use Main, you're actually referring to the Form1.

    }


    ..... Back in Form1, I instantiate Form2 as:

    Form2 f = new Form2(this); // use the this reference to pass Form1 over to Form2 constructor.


    Now let's say in Form1 I have a variable called x declared as:

    public int x = 5; (must be public to access from another class!)


    I could now access this variable in Form2 as:

    Main.x = 4; // Changed variable x in Form1 to 4.
    MessageBox.show(Main.x); // will output 4


    When I used Main.x, i'm actually accessing variable x back in form1. This is pass by value reference.

  6. #6
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: accessing variables in the startup form from other forms

    Quote Originally Posted by JenniferBabe
    When I used Main.x, i'm actually accessing variable x back in form1. This is pass by value reference.
    That's wrong.
    you are still passing "by value", it's just that you are passing an object where there are lots to do with it, the only thing you can't do is call the "new" keyword on it

    If you pass anything in C# byref you'll have to use the "ref" keyword
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  7. #7

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Re: accessing variables in the startup form from other forms

    Jennifer,

    Thanks for the straight answer! It works just like you said. However, I am still unable to access the controls of Form1 from Form2. How could I do something simple like change a textbox in Form1 with the click of a button on Form2, for example?

    Thanks again for the help!

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: accessing variables in the startup form from other forms

    Read the tutorial that has been suggested. It explains exactly how to do that. Given that you posted this same question in the VB.NET forum then I assume that the VB code examples won't be an issue. Despite what you think, the principles are EXACTLY the same whether you're using VB or C#. It's simply the syntax that is different, which is always the case for the two different langauges. If you have to pass an object by value or by reference in VB then you have to pass the same object the same way in C#. No difference, other than the syntax of the language.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: accessing variables in the startup form from other forms

    take a look at the following code, your application should look similar:
    Code:
    public class Form1 : System.Windows.Forms.Form
    {
    	private void btnStart_Click(object sender, EventArgs e)
    	{
    		Form2 f=new Form2(this);
    		f.Show();
    	}
    }
    public class Form2:System.Windows.Forms.Form
    {
    	private System.Windows.Forms.TextBox textBox1;
    	private Form1 frmMain;
    	private const string MY_NAME="ComputerJy";
    	public Form2(Form1 frm)
    	{
    		InitializeComponent();
    		this.frmMain=frm;
    		textBox1.Text=frmMain.Text;
    		frmMain.Text=MY_NAME;
    	}
    }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  10. #10

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Re: accessing variables in the startup form from other forms

    Thanks ComputerJY!

    That works, but If I try to access form1 controls in anywhere else in form2 it doesnt work. For example, inside a button click sub in form2, it doesnt seem to know anything about form2. In your example, how could I change that same texbox on form1 using a button click on form2?

    Thanks again!

  11. #11
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: accessing variables in the startup form from other forms

    Code:
    public class Form1 : Form
    {
    	private Button button1;
    	private System.ComponentModel.Container components = null;
    
    	public Form1()
    	{
    		InitializeComponent();
    	}
    	protected override void Dispose( bool disposing )
    	{
    		if( disposing )
    		{
    			if(components != null)
    			{
    				components.Dispose();
    			}
    		}
    		base.Dispose( disposing );
    	}
    	private void InitializeComponent()
    	{
    		this.button1 = new Button();
    		this.SuspendLayout();
    		this.button1.Location = new System.Drawing.Point(40, 32);
    		this.button1.Name = "button1";
    		this.button1.TabIndex = 0;
    		this.button1.Text = "button1";
    		this.button1.Click += new System.EventHandler(this.button1_Click);
    		this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    		this.ClientSize = new System.Drawing.Size(292, 266);
    		this.Controls.Add(this.button1);
    		this.Name = "Form1";
    		this.Text = "Form1";
    		this.ResumeLayout(false);
    
    	}
    
    	[STAThread()]public static void Main()
    	{
    		Application.EnableVisualStyles();
    		Application.DoEvents();
    		Application.Run(new Form1());
    	}
    
    	private void button1_Click(object sender, System.EventArgs e)
    	{
    		Form2 f=new Form2(this);
    		f.Show();
    	}
    }
    public class Form2:Form
    {
    	private Button button1;
    	private Form1 frmMain;
    	public Form2(Form1 f)
    	{
    		InitializeComponent();
    		frmMain=f;
    	}
    	private void InitializeComponent()
    	{
    		this.button1 = new Button();
    		this.SuspendLayout();
    		this.button1.Location = new System.Drawing.Point(56, 32);
    		this.button1.Name = "button1";
    		this.button1.TabIndex = 0;
    		this.button1.Text = "button1";
    		this.button1.Click += new System.EventHandler(this.button1_Click);
    		this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    		this.ClientSize = new System.Drawing.Size(292, 266);
    		this.Controls.Add(this.button1);
    		this.Name = "Form2";
    		this.Text = "Form2";
    		this.ResumeLayout(false);
    
    	}
    
    	private void button1_Click(object sender, System.EventArgs e)
    	{
    		frmMain.Text="It changed";
    	}
    }
    If there is anything you don't understand, please just ask
    Last edited by ComputerJy; Aug 7th, 2006 at 12:10 PM.
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  12. #12

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Re: accessing variables in the startup form from other forms

    Thanks again ComputerJY,

    That works great changing the form caption, but if i try to change a textbox contents on form1 the intellisense doenst even show the existing text box (when i type "frmMain."

    How can I change a textbox contents of form1 with a button click on form2?

    Im having a difficult time understanding why the form1 properties are changeable, yet not the properties of controls on form1.

    Thanks again!

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: accessing variables in the startup form from other forms

    When you add a control to a form in C# the IDE creates a member variable for that control which is declared private by default, whihc is as it should be. You cannot access private members externally, as I'm sure you're aware. You can change the modifiers of the control to make it public, but that's the dodgy way. If you do that then you expose absolutely everything about that control to the outside world, including the ability for a completely different object to be assigned in it's place. The "proper" way to do it is to declare your own public properties in the form and use them as a pass-through for the control's properties. That way you expose only those properties that you specifically want to be able to access from outside. You also have the ability to make those properties read-only or write-only if that is appropriate. Of course, you know all this already because you've read part 2 of that tutorial I suggested.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  14. #14
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: accessing variables in the startup form from other forms

    Quote Originally Posted by jmcilhinney
    When you add a control to a form in C# the IDE creates a member variable for that control which is declared private by default, whihc is as it should be. You cannot access private members externally, as I'm sure you're aware. You can change the modifiers of the control to make it public, but that's the dodgy way. If you do that then you expose absolutely everything about that control to the outside world, including the ability for a completely different object to be assigned in it's place. The "proper" way to do it is to declare your own public properties in the form and use them as a pass-through for the control's properties. That way you expose only those properties that you specifically want to be able to access from outside. You also have the ability to make those properties read-only or write-only if that is appropriate. Of course, you know all this already because you've read part 2 of that tutorial I suggested.
    I'm sorry, but won't it be so much easier to declare controls "internal"?
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  15. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: accessing variables in the startup form from other forms

    'Internal' still allows you to access the control in its entirety from anywhere in the project. Convenience is not a valid justification for doing so if that is not what you need. You should strive to keep the scope of everything as narrow as possible. Otherwise, why not just declare everything as 'internal'? If all you need to be able to do is to set the Text property of a TextBox then that is all you should be able to do. You would do that by exposing either a method or read-only property of the form, which will then set the control's property internally. Besides, if your form is declared 'internal', which it should be, then declaring a member 'internal' is no different to declaring it 'public'. A member cannot be accessed somewhere that the type can't, so a public member of an internal type is itself internal.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  16. #16

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Re: accessing variables in the startup form from other forms

    Quote Originally Posted by jmcilhinney
    When you add a control to a form in C# the IDE creates a member variable for that control which is declared private by default, whihc is as it should be. You cannot access private members externally, as I'm sure you're aware. You can change the modifiers of the control to make it public, but that's the dodgy way. If you do that then you expose absolutely everything about that control to the outside world, including the ability for a completely different object to be assigned in it's place. The "proper" way to do it is to declare your own public properties in the form and use them as a pass-through for the control's properties. That way you expose only those properties that you specifically want to be able to access from outside. You also have the ability to make those properties read-only or write-only if that is appropriate. Of course, you know all this already because you've read part 2 of that tutorial I suggested.
    Making the button public produced the behavior I was looking for:

    public System.Windows.Forms.Button button1;

    When you say "the ability for a completely different object to be assigned in it's place. " what exactly do you mean by that?

    Ultimately I will want access to all the properties of a chart control from a second dockable control window. My first thought is that making the chart control public would be a much better solution than passing every property I need. You did get my attention with the your statement about object assignment though, and I would like to understand your point.

    Thanks!

  17. #17

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Re: accessing variables in the startup form from other forms

    just discovered that I can access private controls via the controls prop of the form:

    frmMain.Controls[0].Text = "Hello";

    So Im thinking now that a good solution might be to temporarily make the control(s) in question public (for intellisense) then revert to private and ".Controls[x]" after testing/debugging.

    I still want to understand the implications of just using public control(s) where needed. I never really bought into the "public variables are evil" position in VB6 ... are the argument(s) against public controls pretty much the same for C# ?

    Any thoughts on this?

  18. #18
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: accessing variables and controls in the startup form from other forms

    No, it's not the same.

    It's pretty simpler... When you declare a class attribute to be "Public" it can be accessed from outside your app...

    You can look at it as if your app was an OS and all public attributes were trapdoors for hackers to mess with the functionality
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  19. #19

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Re: accessing variables and controls in the startup form from other forms

    so based on everything ive read on this thread so far, it seems that for my chart control where I need access to msny of the chart control properties, I could safely make it "Internal" and save myself the headache of passing a whole lot of properies around?

    any disadvantages to this approach?

    Thanks for all the great help and advice, everyone, by the way ...

  20. #20
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: accessing variables and controls in the startup form from other forms

    I don't see any disadvantages. since it's the default way in VB.NET...
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  21. #21

    Thread Starter
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046

    Re: accessing variables and controls in the startup form from other forms

    Thanks for all the help, everyone. This thread has been very helpful for me!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width