passing variables between forms again :)

I have read about five different threads about passing variables between forms and none of them have made much sense to me or helped me. I know i am very new and green but can't seem to figure it out. So one more time could some one help me in simple terms. Show me how to be able to access data from one form to the next. I am wanting to for example access a string that i have assigned in form1 and use it in form 2. Don't know how to do it. I am using VS 2005 C# Thanks for any help with me being so dense.

Answer this question

passing variables between forms again :)

  • Matthew Devine

    Form1 ...

    using System;

    using System.Drawing;

    using System.Collections;

    using System.ComponentModel;

    using System.Windows.Forms;

    using System.Data;

    namespace WindowsApplication3

    {

    /// <summary>

    /// Summary description for Form1.

    /// </summary>

    public class Form1 : System.Windows.Forms.Form

    {

    private System.Windows.Forms.Button button2;

    private System.Windows.Forms.Button button1;

    private System.Windows.Forms.TextBox textBox1;

    public delegate void StringChangedEventHandler (string _Data);

    public event StringChangedEventHandler StringChanged;

    private void OnStringChanged(string _Data) {

    if(this.StringChanged != null) { this.StringChanged(_Data); }

    }

    /// <summary>

    /// Required designer variable.

    /// </summary>

    private System.ComponentModel.Container components = null;

    public Form1()

    {

    //

    // Required for Windows Form Designer support

    //

    InitializeComponent();

    //

    // TODO: Add any constructor code after InitializeComponent call

    //

    }

    /// <summary>

    /// Clean up any resources being used.

    /// </summary>

    protected override void Dispose( bool disposing )

    {

    if( disposing )

    {

    if (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.button2 = new System.Windows.Forms.Button();

    this.button1 = new System.Windows.Forms.Button();

    this.textBox1 = new System.Windows.Forms.TextBox();

    this.SuspendLayout();

    //

    // button2

    //

    this.button2.Location = new System.Drawing.Point(280, 16);

    this.button2.Name = "button2";

    this.button2.TabIndex = 1;

    this.button2.Text = "Send String";

    this.button2.Click += new System.EventHandler(this.button2_Click);

    //

    // button1

    //

    this.button1.Location = new System.Drawing.Point(16, 16);

    this.button1.Name = "button1";

    this.button1.TabIndex = 0;

    this.button1.Text = "New Child";

    this.button1.Click += new System.EventHandler(this.button1_Click);

    //

    // textBox1

    //

    this.textBox1.Location = new System.Drawing.Point(112, 16);

    this.textBox1.Name = "textBox1";

    this.textBox1.Size = new System.Drawing.Size(160, 20);

    this.textBox1.TabIndex = 2;

    this.textBox1.Text = "textBox1";

    //

    // Form1

    //

    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

    this.ClientSize = new System.Drawing.Size(360, 53);

    this.Controls.Add(this.textBox1);

    this.Controls.Add(this.button2);

    this.Controls.Add(this.button1);

    this.Name = "Form1";

    this.Text = "Form1";

    this.ResumeLayout(false);

    }

    #endregion

    /// <summary>

    /// The main entry point for the application.

    /// </summary>

    [STAThread]

    static void Main()

    {

    Application.Run(new Form1());

    }

    private void button1_Click(object sender, System.EventArgs e) {

    Form2 frm = new Form2(this);

    frm.Show();

    }

    private void button2_Click(object sender, System.EventArgs e) {

    this.OnStringChanged(this.textBox1.Text);

    }

    }

    }

    Form 2

    using System;

    using System.Drawing;

    using System.Collections;

    using System.ComponentModel;

    using System.Windows.Forms;

    namespace WindowsApplication3

    {

    /// <summary>

    /// Summary description for Form2.

    /// </summary>

    public class Form2 : System.Windows.Forms.Form

    {

    private System.Windows.Forms.RichTextBox richTextBox1;

    /// <summary>

    /// Required designer variable.

    /// </summary>

    private System.ComponentModel.Container components = null;

    public Form2(Form1 _Parent)

    {

    //

    // Required for Windows Form Designer support

    //

    InitializeComponent();

    _Parent.StringChanged += new WindowsApplication3.Form1.StringChangedEventHandler(_Parent_StringChanged);

    }

    /// <summary>

    /// Clean up any resources being used.

    /// </summary>

    protected override void Dispose( bool disposing )

    {

    if( disposing )

    {

    if(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.richTextBox1 = new System.Windows.Forms.RichTextBox();

    this.SuspendLayout();

    //

    // richTextBox1

    //

    this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;

    this.richTextBox1.Location = new System.Drawing.Point(0, 0);

    this.richTextBox1.Name = "richTextBox1";

    this.richTextBox1.Size = new System.Drawing.Size(292, 273);

    this.richTextBox1.TabIndex = 0;

    this.richTextBox1.Text = "";

    this.richTextBox1.TextChanged += new System.EventHandler(this.richTextBox1_TextChanged);

    //

    // Form2

    //

    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

    this.ClientSize = new System.Drawing.Size(292, 273);

    this.Controls.Add(this.richTextBox1);

    this.Name = "Form2";

    this.Text = "Form2";

    this.ResumeLayout(false);

    }

    #endregion

    private void richTextBox1_TextChanged(object sender, System.EventArgs e) {

    }

    private void _Parent_StringChanged(string _Data) {

    this.richTextBox1.AppendText(_Data + "\n");

    }

    }

    }

    I just mocked it up quick in 1.1 but the exact same methodology works in 2.0 ... note you can also create unlimited children and they all receive the event from the parent.

    Cheers,

    Greg


  • Thund75

    how would you save for say a couple of strings to a text file. These strings are independant from each other. I guess i would need to save it once i appended it in my form 2 and then be able to access it in my form 1. I will be using this info (from the text file) to compare against my RFID tags info coming from the serial port in Form 1. I then will need to know how to clear only certain parts of the text file when the user wants to remove a person from the list of entrys. Right now this is what i am doing.

    private void textBox2_TextChanged(object sender, EventArgs e)

    {

    personnel = textBox2.Text; // This is input by the user

    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

    {

    }

    private void textBox1_TextChanged(object sender, EventArgs e)

    {

    clearance = textBox1.Text; // This is also input by the user

    }

    private void textBox3_TextChanged(object sender, EventArgs e)

    {

    }

    private void button1_Click(object sender, EventArgs e) // This button click adds the personnel to the list if everything is ok. and then converts it to ascii hex. it also clears the text boxes

    {

    together = personnel;

    together += " ";

    together += clearance;

    bool test1 = String.Compare(textBox1.Text, String.Empty) == 0;

    bool test2 = String.Compare(textBox2.Text, String.Empty) == 0;

    bool test3 = String.Compare(textBox1.Text, "Maximum") == 0;

    bool test4 = String.Compare(textBox1.Text, "Entry") == 0;

    if ((test1 == true || test2 == true) || (test3 == false && test4 == false))

    {

    textBox1.Text = "";

    textBox2.Text = "";

    MessageBox.Show("Invalid Entry Please Try Again");

    }

    else

    {

    listBox1.Items.Add(together);

    }

    encoded += "80";

    byte[] bytes1 = System.Text.ASCIIEncoding.ASCII.GetBytes(personnel);

    // bytes contains the integer values for the character code of each individual character, now you just have to convert from int to hex.

    foreach (int i in bytes1)

    {

    encoded += Convert.ToString(i, 16).ToUpper();

    }

    encoded += "5F";

    byte[] bytes2 = System.Text.ASCIIEncoding.ASCII.GetBytes(clearance);

    // bytes contains the integer values for the character code of each individual character, now you just have to convert from int to hex.

    foreach (int i in bytes2)

    {

    encoded += Convert.ToString(i, 16).ToUpper();

    }

    encoded += "31";

    textBox3.Text = encoded;

    textBox1.Text = "";

    textBox2.Text = "";

    }

    private void button2_Click(object sender, EventArgs e) // this button click removes the personnel if everything is ok and clears the text boxes.

    {

    together = personnel;

    together += " ";

    together += clearance;

    bool test1 = String.Compare(textBox1.Text, String.Empty) == 0;

    bool test2 = String.Compare(textBox2.Text, String.Empty) == 0;

    bool test3 = String.Compare(textBox1.Text, "Maximum") == 0;

    bool test4 = String.Compare(textBox1.Text, "Entry") == 0;

    if ((test1 == true || test2 == true) || (test3 == false && test4 == false))

    {

    textBox1.Text = "";

    textBox2.Text = "";

    textBox3.Text = "";

    MessageBox.Show("Invalid Entry Please Try Again");

    }

    else

    {

    listBox1.Items.Remove(together);

    textBox1.Text = "";

    textBox2.Text = "";

    textBox3.Text = "";

    }

    }

    I tried to comment my code by the button click defs. This is my ie form 2 (AddRemovePersonnel)


  • MagicCity33

    I would like an example of the event based method. Is this what the button clicks in the form are using ie.

    private void button2_Click(object sender, EventArgs e)

    Greatly appreciated

    Colt


  • Piotr_S

    Going to bed got a 9:00 class. Thanks for all your help i will check to see if you pstd anything in the morning.

    Thanks again

    Colt


  • Macca

    The major difference between the methods is whether or not the data is changing and whether or not the other forms need to be made aware of this change. A concept you might also want to read up on is the "Observer" pattern as it handles this as well.

    Greg


  • Craig Lichtenstein - MSFT

    Generally the easiest way is to make a property (accessor method) on the form that has the variable and access it that way. Another method if this data is changing often is to use an event to signal the second form that the data has changed.

    Another way of doing this is to let a ternary "global" object hold the data and both forms interact with this object ...

    Is this data often updated and the other form needs to be notified of the changes I can provide you a quick example of any/all of these methods though I personally use the event based method the most.

    Cheers,

    Greg


  • Gregfig

    Thank you both I am going to try your suggestions right now and will let you know what i come up with.

    Thanks

    Colt


  • SaLLuComp

    Is there any way to hold the data once appended. What i am trying to say is that if i add data to a text box when i am debugging and i close the application and open it up again the data is lost in my list box. Is this just because i am debuggin or when i am using the finished product will the data stay.
  • IJay

    hi,

    1) make a private filed and a public property in form 2 like

    2) use constracter to recieve the value

    3) you can deal with previous 2 ways by a method in your first form

    this code contain either ways

    form 1


    public partial class Form1 : Form

    {
    //this form contain one button

    public Form1()
    {
    InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
    //button to open form2

    string myvariable = "some text here";
    ////first way pass variable through property

    //Form2 frm = new Form2();

    //frm.Mystring = myvariable;

    //frm.ShowDialog();

    //second way by useing contracter

    Form2 frm = new Form2(myvariable);
    frm.ShowDialog();
    }
    }


    form 2




    public partial class Form2 : Form

    {
    //this form contain one textbox

    // first way get variable through properties

    //field

    private string _string;
    //property

    public string Mystring
    {
    get { return _string; }
    set { _string = value; }
    }
    public Form2()
    {
    InitializeComponent();
    // when the form load display mystring in the textbox

    textBox1.Text = _string;
    }

    //second way get variable through a new constractor

    public Form2(string mystring)
    {
    InitializeComponent();
    // when the form load display mystring in the textbox

    textBox1.Text = mystring;
    }
    }


    hope this helps



  • NTCin Bham

    Two key-words:

    1. "internal" (or "public")

    2. "static" (otherwise you're forced to instantiate it instead of accessing it directly from another class/form)

    In your Form1 class define your variable giving it appropriate accessibility: either "internal" or "public" (I always choose "interna" unless I write a shared module/DLL). Obviously, this variable appears within the class and outside of any methods:

    partial class Form1 : Form {

    internal static string myString = "modify from another class of the same assembly";
    public static bool Modified = false;

    private void Form1_Load(Object sender, EventArgs e) {

    // whateber code you have here, including trigger for Form2 ..........
    }

    Now, in your Form2 you'll be able to see and modify either one (or both) of the above variables ("myString" and/or "Modified") - just type in your Form2 class:

    Form1.myString or Form1.Modified (intellisense will show you both of them).

    Good luck.


  • Matt Langley

    yes you would need to save it to some form of persistence ... say a text file ... you could then reload the data when your started back up.

    Greg


  • Chris Dunaway

    Why not store these items in their own class


  • skrymsli

    03r603 wrote:
    how would you do that I do want to explain my issue again just to clarify. I have a main form where i open a second form (add remove personnel). I want everytime that i add a person or remove a person, the main form should know about it. Because the main form will be using this new info actively. This seems so simple yet the more i try the bigger the mountain gets.

    what is this personnel a struct , array , datatable ... what



  • noobie

    how would you do that I do want to explain my issue again just to clarify. I have a main form where i open a second form (add remove personnel). I want everytime that i add a person or remove a person, the main form should know about it. Because the main form will be using this new info actively. This seems so simple yet the more i try the bigger the mountain gets.
  • passing variables between forms again :)