Solved

accessing other forms' controls

Posted on 2006-11-10
13
215 Views
Last Modified: 2010-04-16
HI Guys,
           I have a main form Form1 that starts my win application. There is a DataGridView control on it. Then there's another form Form2 that is called from one of the main menu items. It has a textbox and a button on it. After I input a value into the textbox and press the button excution goes to Form2 's button_click event handler from which I would like to access Form1's DataGridView control.
        I tried to make the DGV  public in Form1's InitializeComponent() but to no effect, I can't see no   form1' s public variables from Form2. Need your help on this one :)

Thanks a lot,
Cheers,
serge
0
Comment
Question by:Autofreak
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
13 Comments
 
LVL 15

Expert Comment

by:ozymandias
ID: 17918306
How is Form2 getting a refernce to Form1  and whgat is that reference ?
If that reference is of type Form you wont be able to see your public variables because they belong to the subtype of your main form.

If in Form2 you have a reference (parent or whatever) to Form1 of type Form then do :

Form1 f1 = (Form1)parent;

Now you have a reference that will expose those public variables.
0
 
LVL 3

Expert Comment

by:bromose
ID: 17921413
You could make Form 1 an Singleton:

public class Form1 : Form
{
     private static Form1 theInstance;

     private Form1()
     { .
       .
     }

    public static Form1 TheInstance {
      get{
              if(theInstance==null)
                 theInstance = new Form1();
              return theInstance;
}}
   public DataGridView Grid { { get { return dataGreidView1;}}

.
.
From Form 2:

Form1 f = Form1.TheInstance;
DataGridView g = f.Grid;


0
 

Author Comment

by:Autofreak
ID: 17938860
Hi ozymandias, Could you elaborate and provide a workin example of the method you are suggesting?

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 15

Accepted Solution

by:
ozymandias earned 250 total points
ID: 17938939
OK.

class myclass
      {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
                  // create an instance of Class2 referenced as a Class2
                  Class2 x = new Class2();
                  // both the SubClassProperty and the inherited baseClassProperty are acessible.
                  Console.WriteLine(x.BaseClassProperty);
                  Console.WriteLine(x.SubClassProperty);

                  // create a Class2 referenced as a Class1
                  Class1 y = new Class2();
                  // we can get at the BaseClassProperty
                  Console.WriteLine(y.BaseClassProperty);
                  // but we can't get at the SubClass property because even though y is a Class2
                  // it is referened as a Class1 and a Class1 does not have a SubClassProperty.
                  
                  //Console.WriteLine(y.SubClassProperty); // <-- compile error !!!!!!!

                  // we can cast it to a Class2 to access thuis poperty
                  Class2 z = (Class2)y;
                  Console.WriteLine(z.BaseClassProperty);
                  Console.WriteLine(z.SubClassProperty);


            }
      }


      class Class1{

            public string BaseClassProperty = "foo";

      }

      class Class2 : Class1{

            public string SubClassProperty = "bar";

      }
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17938967
In your case you have a class called Form1 that is derived from System.Windows.Form.
You have given it a public property of type DataGridView but this property is a property of the Class Form1, not of the class System.Windows.Form.
From your other form when you reference your Form1 it is AS a System.Windows.Form and therefore this property is not acessible.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17939053
Also, I just noticed this :

>>I tried to make the DGV  public in Form1's InitializeComponent()

The DGV will not be public unless you declre it as such you can either do this in design mode by selecting the DGV and then setting its modifier property in the properties pane to public or by editing the code in your form one and changing the :

private DataGridView dataGriudView1;

to

public DataGridView dataGriudView1;
0
 

Author Comment

by:Autofreak
ID: 17942137
ozymandias,
                   If I used inheritance Form2: Form1 then my second form Form2 would not only provide me with access to Form1's public fields, what I want,  but olso, what I don't want, assume all the properties that I don't need like shape and controls. Form2 must not be based in Form1, only have a reference to a Form1 object.  


Serge


0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17942176
No, that is not what I am suggesting at all.

Both of your Forms derive from/inherit Form.
In Form1 you have added a public property.
The reference to Form1 in Form2 is of type Form which means you cannot access the added property,
If you make the reference to Form1 in Form2 of type Form1 then you will be able to acess the property, if it if ot type Form then you wont.

If this is not clear please post your code for Form1 and Form2.
0
 

Author Comment

by:Autofreak
ID: 17942180
bromose , Thanks for the example. Heard about the model before, never actually has a pleasure to implement one. I am not sure yet, but it seems to be a little off my target. I will let you know if I have any questions tomorrow.

Thanks a lot,
Serge
0
 

Author Comment

by:Autofreak
ID: 17942238
ozymandias,
                  I am not sure if what you meant is what I put into code below. Please let me know, it seems to work perfectly now . Thanks, Serge

__________________________________________________________________________

 public partial class Form1 : Form
    {
        Form2 form2;
        public string str;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            form2.Show();
           
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            form2 = new Form2(this);          
       
        }
    }


public partial class Form2 : Form
    {
        Form1 form1; //declare the main form
        public int interg;


        public Form2(Form1 parentForm)
         {


            InitializeComponent();
            form1 = parentForm;
           
           
        }
    }
}

 static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17942629
Yes. That looks OK.

The reference to form1 one on Form2 is of type Form1 :

    Form1 form1; //declare the main form

therefore you can access the public string str that you have decalred in Form1.


0
 

Author Comment

by:Autofreak
ID: 17948925
Great then!!

bromose,
              it's an interesting concept to play around but I don't see yet how it fits the problem. The method we created with ozymandias seems like more straighforward for this type of solution. Thanks a lot.

Serge

0
 
LVL 3

Expert Comment

by:bromose
ID: 17949386
Just a final comment. The Singleton design pattern is in the factory pattern family, wich are famus for solving the problem of "getting a link" an object where you not are the obvius creator. Reading Your problem I beleve that you problem is within this category, so I would encurage you to study the factory patterns - It has helped me at lot in my time as programmer to study patterns ;-)

Best Regards,
Kaj Bromose
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How do I hide MVVM menu items in WPF/XAML? 1 56
linq, c# 8 52
pVarablies are clearing but do not think i am reloading page 1 20
What are MicroServices? 4 69
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …
Suggested Courses

710 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question