Page 2 of 3 FirstFirst 123 LastLast
Results 11 to 20 of 22

Thread: passing variables bitween two form in C#

  1. #11
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default

    Oh I think I found the error
    above I have
    Code:
    //form2.TextChanged += new System.EventHandler(UpdateText);
    when it should be
    Code:
    //form2.txtBoxB.TextChanged += new System.EventHandler(UpdateText);
    and me look like a dummy
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  2. #12
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default The right and proper way

    Form1.cs
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace FormsShareVar
    {
        public partial class Form1 : Form
        {
            Form2 form2;
            public Form1()
            {
                InitializeComponent();
    
                form2 = new Form2();
                form2.RegisterOutsideDelegateOnEventTextChange(new System.EventHandler(UpdateText));
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                form2.ShowDialog();
            }
    
            public void UpdateText(object sender, EventArgs e)
            {
                this.txtBoxA.Text = ((TextBox)(sender)).Text;
            }
        }
    }
    Form2.cs
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace FormsShareVar
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
    
            public void RegisterOutsideDelegateOnEventTextChange(EventHandler eventDel)
            {
                this.txtBoxB.TextChanged += eventDel;
            }
        }
    }
    No overkill this time, LOL.
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  3. #13
    Join Date
    Jul 2006
    Posts
    20
    Rep Power
    0

    Default

    I saw your last code, it seems gooder than the previous but as I was writing my notes about it, here they are, it will be helpful for others.

    notes related with previous page code
    Somethings are wrong in your code. Your delegates implementation is not good. You don't need to implement textBox1_TextChanged callback in Form2. Since you have already associated EventHandler delegate to form2.TextChanged event the only thing you have to do is to implement UpdateText which answer to your TextChanged event. Concerning your UpdateText prototype it is not good. Endeed EventHandler delegate point to method which take the folowing argument:
    Object,
    EventArgs.

    Here below your previous code with my own corrections.

    Ps: excuse my english if it is sometimes wrong.



    Form1.cs
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace FormsShareVar
    {
        public partial class Form1 : Form
        {
            Form2 form2;
            public Form1()
            {
                InitializeComponent();
                form2 = new Form2();
                form2.Tag = this;
                form2.txtBoxB.TextChanged += new System.EventHandler(UpdateText);
    
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                form2.ShowDialog();
            }
    
            
            public void UpdateText(Object sender, EventArgs e)
            {
                // sender object is Form2 TextBox, so you can do the following cast
                TextBox txtbox = sender as TextBox;
                this.txtBoxA.Text = txtbox.Text;
            }
            
        }
    }
    Form2.cs
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace FormsShareVar
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
           // I suppress textBox1_TextChanged callback
       }
    }
    Program.cs
    Code:
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    
    namespace FormsShareVar
    {
        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());
            }
        }
    }
    Form1.Designer.cs
    Code:
    namespace FormsShareVar
    {
        partial class Form1
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
            #region Windows Form Designer generated code
    
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.button1 = new System.Windows.Forms.Button();
                this.txtBoxA = new System.Windows.Forms.TextBox();
                this.SuspendLayout();
                // 
                // button1
                // 
                this.button1.Location = new System.Drawing.Point(101, 124);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(91, 24);
                this.button1.TabIndex = 0;
                this.button1.Text = "button1";
                this.button1.UseVisualStyleBackColor = true;
                this.button1.Click += new System.EventHandler(this.button1_Click);
                // 
                // txtBoxA
                // 
                this.txtBoxA.Location = new System.Drawing.Point(96, 57);
                this.txtBoxA.Name = "txtBoxA";
                this.txtBoxA.Size = new System.Drawing.Size(100, 20);
                this.txtBoxA.TabIndex = 1;
                // 
                // Form1
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(292, 273);
                this.Controls.Add(this.txtBoxA);
                this.Controls.Add(this.button1);
                this.Name = "Form1";
                this.Text = "Form1";
                this.ResumeLayout(false);
                this.PerformLayout();
    
            }
    
            #endregion
    
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.TextBox txtBoxA;
        }
    }
    Form2.Designer.cs
    Code:
    namespace FormsShareVar
    {
        partial class Form2
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
            #region Windows Form Designer generated code
    
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.txtBoxB = new System.Windows.Forms.TextBox();
                this.SuspendLayout();
                // 
                // txtBoxB
                // 
                this.txtBoxB.Location = new System.Drawing.Point(96, 126);
                this.txtBoxB.Name = "txtBoxB";
                this.txtBoxB.Size = new System.Drawing.Size(100, 20);
                this.txtBoxB.TabIndex = 2;
                this.txtBoxB.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
                // 
                // Form2
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(292, 273);
                this.Controls.Add(this.txtBoxB);
                this.Name = "Form2";
                this.Text = "Form2";
                this.ResumeLayout(false);
                this.PerformLayout();
    
            }
    
            #endregion
             
            // In the previous code txtBoxB was private, public is required here
            public System.Windows.Forms.TextBox txtBoxB;
        }
    }
    Rakoun
    /&#176;\
    Pa konèt mové, dèyè do sé on péyi.

  4. #14
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default

    I prefer to use the private for the textboxA. My style. If I was in a rush I would change it to public but I sometimes like to know changes in a class even a year after I make them and I will see the added function OutsideRegister than a change from private to public on the textboxA. In this case, the private is as good as the ousidefunction because one year from now the class can still be using the public update, ie no can break after time. However as a general practice, I sometime overcode even when I can do it a quicker way just to remember what I am doing. Just my style, apart from that it is just apples and oranges. I could use public if I needed. I am not advising anyone to do it my way. It a system that I am very used to.

    I also left the code as
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    when I only needed
    Code:
    using System;
    using System.Windows.Forms;
    because I want a beginner to see that C# has everything spellt out, ie what the prgram should do in detail, but the designer sort of abstracts that. Hopefully, they accept the abstraction and then get into the detail when they are ready.
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  5. #15
    Join Date
    Dec 2002
    Posts
    500
    Rep Power
    0

    Default

    Theres a simpler way its called Binding, its been around since .NET just came out.


    this is in the parent form :
    Code:
    		private void uiBtnPopup_Click( object sender, EventArgs e )
    		{			
    			PopupForm popup = new PopupForm( );
    
    			popup.BindToData(this.uiLblData, "Text" );
    			popup.Show( );
    		}
    the BindToData method is implemented in the Sub form as :
    Code:
    		private void uiBtnClose_Click( object sender, EventArgs e )
    		{
    			this.uiTxtData.DataBindings.Clear( );
    			this.Close( );
    		}
    
    		public void BindToData(object obj, string property)
    		{
    			this.uiTxtData.DataBindings.Add( "Text", obj, property );		
    		}
    	}
    you can always do a simple bind to an object like so...
    even if the simple object is as complex as a Form

    and you can bind more if you want to
    Code:
    		private void uiBtnClose_Click( object sender, EventArgs e )
    		{
    			this.uiTxtData.DataBindings.Clear( );
    			this.uiTxtUserName.DataBindings.Clear( );
    			this.uiTxtPassword.DataBindings.Clear( );
    			this.Close( );
    		}
    
    		public void BindToData(object obj, string property)
    		{
    			this.uiTxtData.DataBindings.Add( "Text", obj, property );		
    		}
    
    		public void BindToUserName(object obj, string property)
    		{
    			this.uiTxtUserName.DataBindings.Add( "Text", obj, property );		
    		}
    
    		public void BindToPassword(object obj, string property)
    		{
    			this.uiTxtPassword.DataBindings.Add( "Text", obj, property );		
    		}
    	}
    Last edited by icymint3; Aug 12, 2006 at 08:55 PM.
    Cultured in Aggression and Koding like a Warrior!!
    “Common sense is instinct. Enough of it is genius.” - George Bernard Shaw.
    "The significant problems we face cannot be solved by the same level of thinking that created them." - Albert Einstein

  6. #16
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default

    Great work, icymint.

    I didn't see this way either.
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  7. #17
    Join Date
    Jul 2006
    Posts
    20
    Rep Power
    0

    Default

    Yes, good idea!

    Rakoun
    /&#176;\
    Pa konèt mové, dèyè do sé on péyi.

  8. #18
    Join Date
    Dec 2002
    Posts
    500
    Rep Power
    0

    Default

    i think we overlooked his problem though, reading his post again it looks as if he does not want to call and extra methods in his handler that opens the sub-form. as in

    Code:
    Form sub = new SubForm();
    sub.Show();
    the SubForm should magically know where to put its data.
    theres a way to do that but it leads to coupling (bad design). but for a small/simple project it should be ok. it uses the singleton pattern.

    There is one and only one instance of the MainForm and it is accessed as a static member of the MainForm Class

    Code:
    class MainForm
    {
       private MainForm() // make the constructor private
       {
          ...
       }
    
       ...
    
       private static MainForm m_sMainFormInstance = new MainForm(); // static member
       public static MainForm MainFormInstance // static property to access it
       { 
          get{ return m_sMainFormInstance; } 
       }
    
    }

    then you can reference and set properties in the MainFormInstance whenever and from wherever.

    Code:
    MainForm mf = MainForm.MainFormInstance;
    
    mf.uiTxtData.Text = this.uiTxtData.Text;
    mf.uiTxtUserName.Text = this.uiTxtUserName.Text;
    mf.uiTxtPassword.Text = this.uiTxtPassword.Text;
    Last edited by icymint3; Aug 13, 2006 at 12:25 PM.
    Cultured in Aggression and Koding like a Warrior!!
    “Common sense is instinct. Enough of it is genius.” - George Bernard Shaw.
    "The significant problems we face cannot be solved by the same level of thinking that created them." - Albert Einstein

  9. #19
    Join Date
    Dec 2002
    Posts
    500
    Rep Power
    0

    Default

    there is another similar solution put your data in a seperate class and make it available in some static(shared) property, the bind to it from both forms, i think it is possible. now you have your data seperated from the UI that manipulates it. its a bit cleaner, and the Coupling is intentional so we will call it Cohesion

    Code:
    class UserData : DataSet ... // this makes it binding aware
    create shared instances of DataRows from the Strongly typed DataSet
    Code:
    class AccessibleData
    {
       public static UserData.Person Person = new UserData.Person();
       public static UserData.UniversityRecords UniversityRecords = new UserData.UniversityRecords ();
    }
    bind the DataRow to the MainForm
    Code:
    class MainForm
    {
       public void MainForm_Load(...)   
       { 
          this.uiTxtFirstName.DataBindings.Add("Text", AccessibleData.Person, "FirstName");
    
          this.uiTxtLastName.DataBindings.Add("Text", AccessibleData.Person, "LastName");
          ...
          ...
       }
    
       ...
       ...
    
    }
    bind the DataRow to the SubForm
    Code:
    class SubForm
    {
       public void SubForm_Load(...)   
       { 
          this.uiTxtFirstName.DataBindings.Add("Text", AccessibleData.Person, "FirstName");
    
          this.uiTxtLastName.DataBindings.Add("Text", AccessibleData.Person, "LastName");
    
          this.uiTxtAddressStreet.DataBindings.Add("Text", AccessibleData.Person, "AddressStreet");
    
          this.uiTxtAddressCity.DataBindings.Add("Text", AccessibleData.Person, "AddressCity");
    
          ...
          ...
       }
    
       ...
       ...
    
    }

    NB dont try to run the code as is, it was not taken from one of my projects or tested like the rest.(especially the syntax for creating a datarow that was defined in the Typed DataSet, its not far from it though)
    Last edited by icymint3; Aug 13, 2006 at 12:45 PM.
    Cultured in Aggression and Koding like a Warrior!!
    “Common sense is instinct. Enough of it is genius.” - George Bernard Shaw.
    "The significant problems we face cannot be solved by the same level of thinking that created them." - Albert Einstein

  10. #20
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default

    I like the last approach using 'cohesion' approach because for multiple windows transparency would be helpful, and as you say it depends on if it is a simple project or not. The simplier project has a great solution in the event driven model, or the databinding method, and consistency can be applied for multiple variables easily.

    I had thought that he (A.I) might prefer to go with the simple databinding, unless he has the need to use behaviours caused by static calls, windows, variables, but now I think that some way to initialize the form may be useful depending, but a simple "global(member) form in the scope(class) that it is used" would have lasting values while it is opened and closed, and no need to reinitialize, but it depends on how he wants to initialize his form with which variables. I cannot see anyother way that is why I thought that the simple databinding was what he needed. That could satisfy his conditions in post one. I think, but not certain.
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

Posting Permissions

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