Access variable from another form in Visual Studio with c#

12,851

You are on the right path, you should not expose controls or variables directly to client code.

Create a read only property in the form/class you want to read the value from:

//Form2.cs
public string MyVar{get{ return textBoxt17.Text;}}

Then, being form22 the instance variable of your already loaded Form2 form class. Then, from any client code that has a reference to it, you can read the value of the property:

string myVal = frm22.MyVar;

EDIT:

Ok based in your last comment, you have a variable in Florm1 and want to access it from Form2, the principle is the same as the previous example, but instead of exposing a control property you now expose a private variable, and instead of living in Form2 it now lives in Form1:

//Form1.cs
private string _myVar = string.Empty

public string MyVar
 {
    get
    { 
       return _myVar ;
    }
    set
    { 
       if(_myVar != value)
           _myVar = value;
    }
 }

The property is now read/write so you can update its value from client code

//From From2, assuming you have an instance of Form1 named form1:
string val = form1.MyVar;
...
form1.MyVar = "any";
Share:
12,851
Stevan Marjanović
Author by

Stevan Marjanović

Updated on June 04, 2022

Comments

  • Stevan Marjanović
    Stevan Marjanović almost 2 years

    I'm using c# and Visual Studio. I want to access a variable from another form. I've found some things like:

    textBox1.Text = form22.textBoxt17.Text;
    

    But I don't want to access a textBox value, I just want to access a variable. I've tried this:

    string myVar1 = Form2.myVar2;
    

    But that doesn't work.

    Any help?

    Update This is what I've got now:

            private string _firstName = string.Empty;
            public string firstName
            {
                get
                {
                    return _firstName ;
                }
                set
                {
                    if (_firstName != value)
                        _firstName = value;
                }
            }
    

    In formLogin (where the variable is located), just below public partial class formLogin : Form

    Then, later in code, inside button on click event:

                OleDbCommand command2 = new OleDbCommand();
                command2.Connection = connection;
                command2.CommandText = "select firstName from logindb where username = '" + txtUsername.Text + "' and password = '" + txtPassword.Text + "'";
                firstName = command2.ExecuteScalar().ToString();
    

    I write this in formAntonyms (from where I want to access the variable) in formLoad event:

            formLogin fli = new formLogin();
            lblName.Text = fli.firstName;            
    

    The problem with all this is that, when formAntonyms opens, lblName is still empty, instead of showing the users name. What am I doing wrong, I've done all the steps right...